tags:

views:

84

answers:

3

I have a LINQ question. Let's say I have a database with the following values:

===================
Date,product,orders
-------------------
1/2/2003,apple,3
1/2/2003,orange,5
1/3/2003,orange,6
1/4/2003,grape,2
===================

How can I use LINQ to get a result that groups the items by date and puts them into a variable that looks like this:

==========================
Date, Apple, Orange, Grape
--------------------------
1/2/2003,3,5,0
1/3/2003,0,6,0
1/3/2003,0 0,2
==========================

Any help would be much appreciated. Thanks!

+4  A: 

Here the test I done:

var data = new []{
    new { Date = new DateTime(2003, 1, 2), Product = "apple", Orders = (int?) 3 },
    new { Date = new DateTime(2003, 1, 3),Product =  "orange", Orders = (int?) 5 },
    new { Date = new DateTime(2003, 1, 4), Product = "grape", Orders = (int?) 2 },
    new { Date = new DateTime(2003, 1, 4), Product = "grape", Orders = (int?) null }
};

var result = data.GroupBy(x => x.Date)
                 .Select(g => new {
                   Date = g.Key,
                   Apples = g.Where(x => x.Product == "apple").Sum(x => x.Orders),
                   Oranges = g.Where(x => x.Product == "orange").Sum(x => x.Orders),
                   Grapes = g.Where(x => x.Product == "grape").Sum(x => x.Orders)
                 });

The result for the test data does not contain nulls, but 0 for Apples, Oranges, and Grapes.

Obalix
How can I handle a situation where Apples = g.Where(x => x.Product == "apple").Sum(x => x.Orders),returns a null value? can I have it return a 0 instead of a null in this case?
Soo
See modified solution. I have not tested it but AFAIK it should work when x.Orders returns null.
Obalix
I'm getting the following error: Operator '??' cannot be applied to operands of type 'double' and 'int'Thanks for the help so far
Soo
Figured it out. It needs to follow this form:Apples = (int?)g.Where(x => x.Product == "apple").Sum(x => x.Orders),But your suggestion of using the coalescing operator lead me on the right track. Thank you very much!
Soo
Acceptance would be greatly appreciated.
Obalix
Accepted! Thanks again! :D
Soo
A: 

Using Linq to SQL, you could do something like;

var query = from p in products orderby p.Date select p;

I'm not sure what you mean by "puts them into a variable".

Mark Milbourne
A: 

try this:

var x = from tb in mytable
        group date by tb.date;
VinTem