Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Datatable Group by and return all columns

Tags:

c#

linq

I have a Datatable

ID  Age Last name   First Name  Sex class   Father_Name Mother_Name Marks
1   20  A   B   M   1   A   B   50
1   20  A   B   M   1   A   B   50
1   20  A   B   M   1   A   B   100
2   15  F   G   F   2   H   J   40
2   15  F   G   F   2   H   J   50

& I want following results after applying Linq Group by

1   20  A   B   M   1   A   B   200
2   15  F   G   F   2   H   J   90

I am able to get the sum but i am not able to get the other columns in LINQ group by

Can anyone help on this

var drResults = from r1 in dtResults.AsEnumerable()
                            group r1 by new 
                                {
                                   MarksSum=  r1.Field<int>("Marks"),

                                }
                                into g
                            select new
                            {


                                    Total = g.Sum(r1=>r1.Field<int>("Marks"))                                   
                            };
like image 553
vicky Avatar asked Dec 15 '22 13:12

vicky


1 Answers

var _result =   from r1 in dtResults.AsEnumerable()
                group r1 by new
                {
                    ID = r1.Field<int>("ID"),
                    Age = r1.Field<int>("Age"),
                    LastName =  r1.Field<int>("LastName"),
                    FirstName = r1.Field<int>("FirstName"),
                    Sex =  r1.Field<int>("Sex"),
                    Class =  r1.Field<int>("class"),
                    Father_Name =  r1.Field<int>("Father_Name"),
                    Mother_Name =  r1.Field<int>("Mother_Name")
                } into g
                select new
                {
                    ID = g.Key.ID,
                    Age = g.Key.Age,
                    LastName =  g.Key.LastName,
                    FirstName = g.Key.FirstName,
                    Sex =  g.Key.Sex,
                    Class =  g.Key.Class,
                    Father_Name =  g.Key.Father_Name,
                    Mother_Name =  g.Key.Mother_Name,
                    TotalMark = g.Sum(x => x.Field<int>("Marks"))
                };
like image 171
John Woo Avatar answered Dec 18 '22 02:12

John Woo