LINQ查询返回一个List<bool>列表

3

我有一个LINQ查询,需要返回一个列表,其中包含如果在特定索引处满足条件,则为truefalse

dataList = {100, 40, 10, 200};
var res = dataList.Select((item, index) => new { item, index }).Any(x => x.item > 50).ToList();

以上方法存在的问题是我无法在结尾处添加ToList()。如果没有它,它只会返回true或false,而我想要一个bool列表。

期望输出 - {true, false, false, true}


数据列表的类型是什么? - undefined
@PranavPatel 整数 List<int> dataList = new List<int>{100, 40, 10, 200}; - undefined
Any(x => x.item > 50) 返回 bool。你不能将 bool 强制转换为列表。 - undefined
1个回答

5

在你的方法中存在许多不必要的代码。
使用带有索引参数的Select方法重载并不需要仅仅测试Select枚举序列中的当前元素是否大于50。

如果你只想要一个与整数数组匹配的布尔值列表,那么可以使用:

int[] dataList = { 100, 40, 10, 200};
var res = dataList.Select(item => item > 50).ToList();

foreach(bool b in res)
   Console.WriteLine(b);

最后,调用Any方法是错误的。当列表中的元素满足条件并停止枚举时,它返回true或false。它不会返回一个IEnumerable,你无法使用ToList()方法将其实例化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接