[英]Why doesn't this LINQ Select expression work
我有一个困难的LINQ表达式,我不知道为什么它不起作用。 我得到的语法错误是
无法从用法中推断
Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)
的参数类型。 尝试显式指定类型参数。
错误出现在第二个Select
语句x.Select
。 我正在尝试从allFactors
获取每个List列表中的一个元素,并将它们添加到一起,并将添加到一起的每个分组中的每个分组保留在tempList
。 换句话说,我想将各个元素放在tempList
并在temp
知道它们的总数。
在代码的前面, allFactors
填充有值。 如何明确指定类型或以其他方式执行此操作。 我不明白为什么它也不能推断类型。
int temp = 0;
//List<List<int>> allFactors = new List<List<int>>();
List<int> tempList = new List<int>();
allFactors.Select(x => x.Select(y => { temp += y; tempList.Add(y); }));
编辑:David L的答案确实修复了语法错误! 不幸的是,通过进一步的测试,我意识到我的代码没有按照我想要的去做。 我真正想要的是获取每个排列,从而每个组仅由列表中的一个元素组成。 举个例子:
List<List<int>> oldList = {{1,2},{3,4}};
List<List<int>> newList = {{1,3},{1,4},{2,3},{2,4}};
我正在寻找将oldList
转换为newList
。 挑战在于我不知道将有多少个嵌套列表,或者每个列表中将有多少个项目。 有任何想法吗? 到目前为止,感谢大家的想法。
无法推断类型,因为您未通过内部select返回任何内容。 结果,编译器没有任何内容可以推断外部选择。
另外,由于没有使用选定的返回值,因此可以使用.ForEach()
。
int temp = 0;
List<List<int>> allFactors = new List<List<int>>();
List<int> tempList = new List<int>();
allFactors.ForEach(x => x.ForEach(y => { temp += y; tempList.Add(y); }));
如果要坚持使用.Select()
,则需要从内部选择中返回值,并将.SelectMany()
用于外部选择。
int temp = 0;
List<List<int>> allFactors = new List<List<int>>();
List<int> tempList = new List<int>();
List<int> selectedList = allFactors.SelectMany(x => x.Select(y =>
{
temp += y;
tempList.Add(y);
return y;
})).ToList();
这将产生一个“扁平化”的List<int>
,它似乎与tempList
的最终目标tempList
。
如果您只想展平“ allFactors”,则可以这样:
var tempList = allFactors.SelectMany(x => x).ToList();
var temp = tempList.Sum();
如果只需要每个列表的第一个元素,则它将是:
var tempList = allFactors.Select(x => x.First()).ToList();
var temp = tempList.Sum();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.