2
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;
4

1 回答 1

6

Linq 提供了一个Count方法的重载,它接受 aFunc<T, bool>并将计算满足该条件的元素的数量:

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

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

int countLessThanZero = roads.Where(t => t.Item3 < 0).Count();
于 2013-08-11T18:24:39.280 回答