c# - 从列表中返回元组计数

标签 c# linq list lambda tuples

List<Tuple<string, string, int>> roads

roads.Add(new Tuple<string, string, int>)("first", "second", 1);
roads.Add(new Tuple<string, string, int>)("first", "second", 2);
roads.Add(new Tuple<string, string, int>)("first", "second", -5);
roads.Add(new Tuple<string, string, int>)("first", "second", 3);

需要显示 item3 < 0 的计数元组

我的变体(不正确):

var r roads.Select(t => t.Item3 < 0).Count;

最佳答案

Linq 提供了 Count 的重载采用 Func<T, bool> 的方法并将计算满足该条件的元素的数量:

int countLessThanZero = roads.Count(t => t.Item3 < 0);

或者,您可以先过滤列表,然后计算过滤列表中的元素数:

int countLessThanZero = roads.Where(t => t.Item3 < 0).Count();

关于c# - 从列表中返回元组计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18175190/

相关文章:

c# - 更改控制台窗口的大小会引发 ArgumentOutOfRangeException

c# - 如何选择 LINQ 数据表连接中的所有列?

列表中第二大值的算法考试示例

c# - 有关在 .NET 中使用消息队列服务总线的问题

c# - 如何使用 Windows SDK 更新 "Additional Clocks"设置

c# - Linq 将数组匹配到列表?

c# - 外键引用在分配 Null 时已具有值异常 Linq to SQL

python - Python 列表中的排序和删除

python - 正确初始化列表

c# - 捕获的 .NET 异常意外为空