Serkan Hekimoglu
Serkan Hekimoglu

Reputation: 4284

LinQ & DataTable Group By Question in C#

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

Upvotes: 2

Views: 18631

Answers (2)

Saeed Amiri
Saeed Amiri

Reputation: 22555

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"))}

Upvotes: 3

Jay
Jay

Reputation: 57919

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")) };

Upvotes: 5

Related Questions