开发者

C# Linq Query - Groupby

I have a datatable that holds data as such:

Date OperationA OperationB OperationC

Today    5
Today               6
Today                          7

Now, I want this to look like:

Date OperationA OperationB OperationC

Today    5          6          7

I've had a look at the LINQ Group by clause, but that seems to seperate the data that is being grouped开发者_如何学JAVA and doesn't keep it within the collection - althought as a LINQ novice, I may be missing something.

Could somebody please advise.

Thanks.


class Operation
{
    public DateTime Date { get; set; }
    public int OperationA { get; set; }
    public int OperationB { get; set; }
    public int OperationC { get; set; }
}

var operations = LoadData();
var result = operations.GroupBy(o => o.Date)
                   .Select(g => new Operation
                    {
                        Date = g.Key,
                        OperationA = g.Sum(o => o.OperationA),
                        OperationB = g.Sum(o => o.OperationB),
                        OperationC = g.Sum(o => o.OperationC)
                    });

P.S: You DB design looks weird. I think the table should look like this:

Date       Operation     Type
2010-1-1      5           A
2010-1-1      6           B
2010-1-1      7           C


LINQ projects - that is, it produces a new sequence based on the input sequence. In other words, it is always read-only, it never writes, never modifies the original sequence, and never has side-effects.

Secondly, GroupBy produces an IGrouping, which is a special kind of IEnumerable<T> with an extra property called Key - that's the single value those items have in common, and were grouped by.

So in your case, GroupBy will create a data structure that is slightly closer to the final goal, by clustering rows by date:

var operationClusters = myDataTable.Rows.OfType<DataRow>().GroupBy(row => row["Date"]);

But you still need to provide the logic for collapsing the values into a single row - for example, 5 is the wanted value and null is not for OperationA column.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜