sooprise
sooprise

Reputation: 23207

Grouping Values With C# And LINQ

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!

Upvotes: 1

Views: 172

Answers (3)

AxelEckenberger
AxelEckenberger

Reputation: 16936

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.

Upvotes: 4

thitemple
thitemple

Reputation: 6059

try this:

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

Upvotes: 0

Mark Milbourne
Mark Milbourne

Reputation: 141

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".

Upvotes: 0

Related Questions