C# 列表<;T>;动态串联
我试图将C# 列表<;T>;动态串联,c#,dictionary,concatenation,generic-list,C#,Dictionary,Concatenation,Generic List,我试图将列表归纳如下- List<Student> finalList = new List<Student>(); var sortedDict = dictOfList.OrderBy(k => k.Key); foreach (KeyValuePair<int, List<Student>> entry in sortedDict) { List<Student> ListFromDict
列表
归纳如下-
List<Student> finalList = new List<Student>();
var sortedDict = dictOfList.OrderBy(k => k.Key);
foreach (KeyValuePair<int, List<Student>> entry in sortedDict) {
List<Student> ListFromDict = (List<Student>)entry.Value;
finalList.Concat(ListFromDict);
}
List finalList=new List();
var sortedDict=dictOfList.OrderBy(k=>k.Key);
foreach(SortedDdict中的KeyValuePair条目){
List ListFromDict=(List)entry.Value;
finalList.Concat(ListFromDict);
}
但没有发生连接。finalList仍然是空的。有什么帮助吗?您可能需要阅读以下文档: 返回值
类型:System.Collections.Generic.IEnumerable
包含两个输入序列的连接元素的IEnumerable 因此,您可能希望使用包含新元素的返回值 或者,您可以使用,它将指定集合的元素添加到列表的末尾 另外,您还可以通过一个简单的LINQ查询来实现您的目标:
var finalList = dictOfList.OrderBy(k => k.Key)
.SelectMany(k => k.Value)
.ToList();
按照规定,Concat
生成一个新序列,而AddRange
实际上将元素添加到列表中。因此,您应该将其改写为:
List<Student> finalList = new List<Student>();
var sortedDict = dictOfList.OrderBy(k => k.Key);
foreach (KeyValuePair<int, List<Student>> entry in sortedDict) {
List<Student> ListFromDict = (List<Student>)entry.Value;
finalList.AddRange(ListFromDict);
}
调用
Concat
不会修改原始列表,而是返回一个新列表——或者说是完全准确的:它返回一个IEnumerable
,将生成两个串联列表的内容,而不修改其中任何一个
您可能想使用AddRange
,它可以满足您的需要:
List<Student> ListFromDict = (List<Student>)entry.Value;
finalList.AddRange(ListFromDict);
Concat
方法不修改原始集合,而是返回带有连接结果的全新集合。所以,要么尝试finalList=finalList.Concat(ListFromDict)
,要么使用修改目标列表的AddRange
方法。其他答案解释了为什么Concat
对您没有帮助,但它们都保留了您原来的循环。没有必要这样做-LINQ已经介绍了:
List<Student> finalList = dictOfList.OrderBy(k => k.Key)
.SelectMany(pair => pair.Value)
.ToList();
List finalList=dictOfList.OrderBy(k=>k.Key)
.SelectMany(pair=>pair.Value)
.ToList();
明确地说,这将替换整个现有代码,而不仅仅是循环体
更简单:)每当你发现自己在使用一个只会构建另一个集合的
foreach
循环时,你是否可以使用LINQ消除该循环是值得一看的。@downvoter需要详细说明,以便我可以修正我的答案?不需要强制转换-因为它是一个KeyValuePair
,值
的类型已经是列表
。(OP的原始代码中的演员阵容也是多余的。)是的,我没有首先关注类型,但我在你回应时看到了。现在它就在那里。另外一个提示:Concat
是一个LINQ扩展方法,所有这些方法都使用列表
作为数据源,但不更改原始集合。所提到的AddRange
是一个正常的List
方法,类似于Add
和Remove
,因此会改变集合。这必须是finalList=finalList.Concat(ListFromDict).ToList()
,因为Concat返回源类型的IEnumerable
,因此,它不能直接分配给列表。
finalList.AddRange((List<Student>)entry.Value);
finalList.AddRange(entry.Value);
List<Student> finalList = dictOfList.OrderBy(k => k.Key)
.SelectMany(pair => pair.Value)
.ToList();