C# 将分层字典转换为列表<;KeyValuePair<;文档、文件>&燃气轮机;()
我有一本类似于C# 将分层字典转换为列表<;KeyValuePair<;文档、文件>&燃气轮机;(),c#,linq,C#,Linq,我有一本类似于Dictionary 我想把那本字典转换成List 哪个是平面系统 目前,我正在使用foreach转换该列表,是否可以使用Linq var documentFileList = RepositoryFactory.FileRepository.GetFiles(_case); var retVal = new List<KeyValuePair<Document, File>>(); if (documentFileList != nul
Dictionary
我想把那本字典转换成List
哪个是平面系统
目前,我正在使用foreach转换该列表,是否可以使用Linq
var documentFileList = RepositoryFactory.FileRepository.GetFiles(_case);
var retVal = new List<KeyValuePair<Document, File>>();
if (documentFileList != null)
{
foreach (var docFileKeyPair in documentFileList)
{
if (docFileKeyPair.Value != null)
{
foreach (var fileEntity in docFileKeyPair.Value)
{
var document = docFileKeyPair.Key as Document;
if (document != null)
{
retVal.Add(new KeyValuePair<Document, File>(document, fileEntity));
}
}
}
}
}
var documentFileList=RepositoryFactory.FileRepository.GetFiles(_case);
var retVal=新列表();
if(documentFileList!=null)
{
foreach(documentFileList中的var docFileKeyPair)
{
if(docFileKeyPair.Value!=null)
{
foreach(docFileKeyPair.Value中的var fileEntity)
{
var document=docFileKeyPair.Key作为文档;
如果(文档!=null)
{
添加(新的KeyValuePair(文档、文件实体));
}
}
}
}
}
提前感谢使用
Linq
,您可以做到这一点
var flattenList = documentFileList.SelectMany(x=>x.Value.Where(v=> v != null).Select(s=> new KeyValuePair<Document, File>(x.Key, s)))
.ToList();
var flattlist=documentFileList.SelectMany(x=>x.Value.Where(v=>v!=null)。选择(s=>newkeyvaluepair(x.Key,s)))
.ToList();
选中此项
foreach
->选择
foreach foreach
->选择many
为什么要使用Linq?你的代码有问题吗?对于大型/大型数据存储,simple For loop比Linq解决方案快得多。@MaciejLos没有代码工作得很好,只是想在Linq中转换它以减少代码行如何从OP代码中包括null
检查。谢谢@HariPrasad