tags:

views:

159

answers:

3

I have a List of Customers

List<Customers> cust = new List<Customers>();
cust.Add(new Customers(){ID=1, Name="Sam", PurchaseDate=DateTime.Parse("01/12/2008")});
cust.Add(new Customers(){ID=2, Name="Lolly" PurchaseDate=DateTime.Parse("03/18/2008")});

I want to show 2 seperate results like:

Purchases by Customer in Yr // Grouping by yr and display id,name
Purchases by Customer in Yr - Month // Grouping by yr then month and display id,name

Also What if i want to order the yr?

Update:

Just one more addition. If I have a field called "Status" in the Customer class with either of these values 'Y', 'N', 'C' standing for yes, no and cancel how will i create a query to give ratio in %

Y - 20% N - 30% C - 50%

+6  A: 

Grouping by year:

var groupByYear = customers.GroupBy(customer => customer.PurchaseDate.Year);

foreach (var group in groupByYear)
{
    Console.WriteLine("Year: {0}", group.Key);
    foreach (var customer in group)
    {
        Console.WriteLine("{0}: {1}", customer.ID, customer.Name);
    }
}

Grouping by year and month:

var groupByYearMonth = customers.GroupBy(customer => 
     new DateTime(customer.PurchaseDate.Year, customer.PurchaseDate.Month, 1));
foreach (var group in groupByYear)
{
    Console.WriteLine("Year/month: {0}/{1}", group.Key.Year, group.Key.Month);
    foreach (var customer in group)
    {
        Console.WriteLine("{0}: {1}", customer.ID, customer.Name);
    }
}

Ordering:

var ordered = customers.OrderBy(customer => customer.PurchaseDate.Year);

All of these use "dot notation" instead of query expressions because they're so simple - but you could use a query expression if you wanted to.

EDIT: For the status part, just use David B's answer.

Jon Skeet
dam you why are you so fast Jon. I was just writing my answer :)
Nathan W
So fast? The question's been up for 20 minutes :)
Jon Skeet
Not all of us sit on here all day Mr Skeet ;) (but I do so I suppose that call isn't really valid)
Nathan W
If I'd been on here all day it certainly wouldn't have taken me 20 minutes to answer ;) (I was on the tube when this question was posted...)
Jon Skeet
A: 

thanks so much Jon. Please see the update to the question

Please can you add this to your original question.
Nathan W
Or add another question! All the folks pursuing points *love* easy questions.
Mark Brittingham
+2  A: 
int total = customer.Count()

var counts = customers.GroupBy( c => c.Status )
  .Select( g => new
  {
    Status = g.Key,
    TheRatio = (g.Count() * 100) / total;
  })
David B
Thank you David.