如何使用计算值创建匿名类型

时间:2015-11-12 19:05:23

标签: c# linq

我们说我有这样的结构:

class Ticket
{
 int Id;
 bool Void;
}

是否可以使用LINQ获取具有这两个聚合属性的匿名类型?

select new {totalVoid = numVoidTickets, totalNonVoid = numNonVoidTickets};

我认为这可能是一种方法:

from t in Tickets
select new { totalVoid = t.Id.Count(x => x.Void == true, 
totalNonVoid = t.Id.Count(x => x.Void == false };

但在我输入t.Idt后,intellisense未显示Count()。

3 个答案:

答案 0 :(得分:7)

t是表达式中的单个项目。

您不需要外部Select /' from`来获取此信息:

var result = new 
{ 
  totalVoid = Tickets.Count(x => x.Void == true), 
  totalNonVoid = Tickets.Count(x => x.Void == false)
};

答案 1 :(得分:2)

如果您希望最小化对数据库的调用次数,可以使用分组在一次调用中执行所有聚合。要对整个集合进行分组,只需使用GroupBy(t => 1)

var results = Tickets.GroupBy(t => 1).Select(t => new
{
    totalVoid = t.Count(o => o.Void == true),
    totalNonVoid = t.Count(o => o.Void == false)
});

答案 2 :(得分:1)

List<Ticket> tickets = new List<Ticket>()
{
    new Ticket{Id=10,Void =true},
    new Ticket{Id=10,Void =true},
    new Ticket{Id=10,Void =true},
    new Ticket{Id=10,Void =false},
    new Ticket{Id=10,Void =false},
    new Ticket{Id=10,Void =true},
    new Ticket{Id=10,Void =true},
};
var result = tickets.GroupBy(x => x.Void)
    .Select(x=>new 
    {
        typeVoid = x.Key,
        coutVoid = x.Count()
    });
foreach (var x in result)
{
    Console.WriteLine("count = {0} type ={1}", x.coutVoid, x.typeVoid);
}