通过LINQ创建匿名对象

时间:2012-09-04 08:16:49

标签: c# linq

我有一个对象:

public class Ticket
{
   public string EventName {get;set;}
   public string Count {get;set;}
   public string Price {get;set;}
   ... other properties;
}

进行测试:

var tickets = new List<Ticket>();
tickets.Add(new Ticket {EventName = "Test", TicketCount = 1, Price = 100});
tickets.Add(new Ticket { EventName = "Test", TicketCount = 2, Price = 200 });
tickets.Add(new Ticket { EventName = "Test2", TicketCount = 1, Price = 50 });

我想获取具有以下属性的匿名对象:EventName, TicketCount, Price 并按事件名称“分组” 对于上面的例子,结果必须是:
匿名对象必须包含两个记录:

EventName = Test, TicketCount = 3, Price = 300
EventName = Test2, TicketCount = 1, Price = 50

我未完成的代码:

var groupedByEvent = tickets.GroupBy(t => t.EventName);
var obj = new {EventName = seatsByEvent.Select(t=>t.Key), TicketCount = seatsByEvent.Sum(???)}

如何解决这个问题?

3 个答案:

答案 0 :(得分:12)

var result = tickets.GroupBy(t => t.EventName)
                    .Select(g  => new { 
                             EventName = g.Key, 
                             TicketCount = g.Sum(t => t.TicketCount), 
                             Price = g.Sum(t => t.Price)
                    });

foreach(var x in result)
     Console.WriteLine("EventName = {0}, TicketCount = {1}, Price = {2}"
                       , x.EventName , x.TicketCount , x.Price);

答案 1 :(得分:4)

var groupedByEvent = tickets.GroupBy(t => t.EventName);

var obj = groupByEvent.Select(group => new {
   EventName = group._Key,
   TicketCount = group.Sum(x => x.TicketCount),
   Price = group.Sum(x => x.Price)
});

答案 2 :(得分:4)

首先,您必须正确设置POCO类:

public class Ticket
{
  public string EventName {get;set;}
  public string Count {get;set;}
  public int Price {get;set;}
  public int TicketCount { get; set; }
}

Price必须是和int,也像TicketCount一样,这必然是总和。

然后linq查询将如下所示:

var events = tickets.GroupBy(t => t.EventName).Select(g => new 
{
  EventName = g.Key,
  TicketCount = g.Sum(t => t.TicketCount),
  Price = g.Sum(t => t.Price)
});