我有一个linq列表选择问题

时间:2012-12-29 17:24:02

标签: linq select

如果您有一个集合/列表<>对象如何从该集合中选择不同的记录/ 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();

由于

2 个答案:

答案 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)

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

您应该使用Where代替Select,或者只是将条件放在Count中:

int completed = list.Count(x => x.Status == "Completed");
int processing = list.Count(x => x.Status == "Processing");