6

I have a object:

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

For test:

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 });

I want to get anonymous object with following properties: EventName, TicketCount, Price and "grouped" by event name.
For the example above the result must be:
anonymous object must contain two records:

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

My not finished code:

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

How to solve this?

3 Answers 3

17
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);
Sign up to request clarification or add additional context in comments.

Comments

5

First you have to set your POCO class right:

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

Price has to be and int and also like the TicketCount, that's necessarily for the sum.

Then the linq query will look like this:

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)
});

Comments

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)
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.