开发者

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!


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.


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


try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜