如果您有一个集合/列表<>对象如何从该集合中选择不同的记录/ List<> ?
例如,我正在执行以下操作,但两者的计数相同:
var list = List<Order>;
list.add( new Order { Status = "Completed" });
list.add( new Order { Status = "Completed" });
list.add( new Order { Status = "Completed" });
list.add( new Order { Status = "Processing" });
var = completed = list.Select(x => x.Status == "Completed").Count();
var = Processing = list.Select(x => x.Status == "Processing").Count();
由于
答案 0 :(得分:2)
嗯,有两个问题和一个简化:
=
和变量名称var
Where
代替Count
Count
的重载更简单,它首先采用谓词... 所以:
var completed = list.Count(x => x.Status == "Completed");
var processing = list.Count(x => x.Status == "Processing");
或者,你可以创建一个“按状态计算”字典:
var counts = list.GroupBy(x => x.Status)
.ToDictionary(g => g.Key, g => g.Count());
var completed = counts["Completed"];
var processing = counts["Processing"];
答案 1 :(得分:1)
您获得的计数相同,因为您创建的结果包含true
和false
值,但是当您计算它们时,它们仍然与集合中的项目一样多。
您应该使用Where
代替Select
,或者只是将条件放在Count
中:
int completed = list.Count(x => x.Status == "Completed");
int processing = list.Count(x => x.Status == "Processing");