3

我有一个对象:

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(???)}

如何解决这个问题?

4

3 回答 3

15
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);
于 2012-09-04T08:20:16.913 回答
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)
});
于 2012-09-04T08:19:34.203 回答
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)
});
于 2012-09-04T08:30:05.067 回答