0

如果您有一个集合/List<> 对象,您如何从该集合/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();

谢谢

4

2 回答 2

2

好吧,有两个问题和一个简化:

  • 你的变量声明不应该有一个=betweenvar和变量名
  • 对于过滤,您应该使用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"];
于 2012-12-29T17:29:54.067 回答
1

您将获得相同的计数,因为您正在创建由truefalse值组成的结果,但是当您计算它们时,它们仍然与集合中的项目一样多。

您应该使用Whereinstead of Select,或者干脆将条件放在Countinstead 中:

int completed = list.Count(x => x.Status == "Completed");
int processing = list.Count(x => x.Status == "Processing");
于 2012-12-29T17:30:09.040 回答