LinQ & DataTable Group By Question in C#

18,512

Solution 1

Since you are grouping by StockCardQuote, the "Explain" value is going to be all of the Explain values from rows with the same StockCardQuote -- it is going to be an IEnumerable<T>, so if Explain is a string, you'll get IEnumerable<string>.

To include this in your select statement, just do

select new { 
    StockCardCode = grp.Key, 
    Quantity = grp.Sum(r => r.Field<decimal>("Quantity")),
    Explanations = grp.Select(r => r.Field<string>("Explain")) };

Solution 2

There is no unique item in your group but you can select the first item and show the fields:

    select 
    new { StockCardCode = grp.Key, 
    Quantity = grp.Sum(r => r.Field<decimal>("Quantity")),
    Explain = grp.First().Select(x=>x.Field<string>("Explain"))}
Share:
18,512
Serkan Hekimoglu
Author by

Serkan Hekimoglu

Objective-C &amp; Java

Updated on June 05, 2022

Comments

  • Serkan Hekimoglu
    Serkan Hekimoglu almost 2 years

    I have a DataTable and stores 4 columns (StockCardCode,Explain,Quantity,BranchCode), and Im grouping them with a LinQ. Code is my key for using Group By. When I write my query, I just can use 2 columns in select statement, how can I show all columns in this query? This query returns me 2 column. I cant use x.Field("Explain") in my query for example.

    var query = from s in incoming.AsEnumerable()
                            group s by s.Field<string>("Stock Card Code")
                                into grp
                                orderby grp.Key
                                select new { StockCardCode = grp.Key, Quantity = grp.Sum(r => r.Field<decimal>("Quantity")) };
    

    incoming: DataTable