【问题标题】:Why doesn't this LINQ Select expression work为什么这个 LINQ Select 表达式不起作用
【发布时间】:2016-06-11 18:28:53
【问题描述】:

我有一个困难的 LINQ 表达式,我不知道为什么它不起作用。我得到的语法错误是

Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>) 的参数类型不能 从用法推断。尝试指定类型参数 明确的。

错误出现在第二条Select 语句x.Select。我试图从allFactors 中获取每个列表列表中的一个元素,并将它们添加在一起,并保留在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 的方法。挑战在于我不知道会有多少嵌套列表或每个列表中有多少项目。有任何想法吗?到目前为止,感谢大家的想法。

【问题讨论】:

  • allFactors的类型是什么?
  • 您的第二个 Select 子句没有返回任何内容。
  • 您是否只想将每个“allFactors”列表的第一个元素放入“tempList”中?
  • @DanielBryars,对不起,我没有澄清。注释掉的变量allFactors 来自代码前面的代码,并且是正确的数据类型。但是,请查看我的编辑,因为我已经澄清了我的问题。

标签: c# linq select


【解决方案1】:

无法推断类型,因为您没有通过内部选择返回任何内容。结果,编译器没有任何可推断的外部选择。

此外,由于您没有使用选定的返回,因此您可以使用.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&lt;int&gt;,这似乎符合您对tempList 的最终目标。

【讨论】:

  • 感谢您的清晰解释!非常有帮助,我只知道如何使用 Linq 并没有意识到 Select 需要返回一些东西。我已经看到了文档,现在我明白你的意思了。请参阅我已澄清问题的编辑。
  • @michaelto20 很高兴为您提供帮助并感谢您的澄清。然而,在这种情况下,由于问题的性质发生了如此巨大的变化,最好创建一个新问题。
  • 好建议,如果您有任何想法,这里是新帖子:stackoverflow.com/questions/37791100/…
【解决方案2】:

如果您只想展平“allFactors”,您可以这样做:

        var tempList = allFactors.SelectMany(x => x).ToList();
        var temp = tempList.Sum();

如果您只需要每个列表的第一个元素,那么它将是:

        var tempList = allFactors.Select(x => x.First()).ToList();
        var temp = tempList.Sum();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多