Harshit Verma
Harshit Verma

Reputation: 21

Error while using Group By in LinQ

i am relatively new to Linq and am trying to group by my Linq query but am getting the error that does not contain Field value.

Below is my linq query. Can anyone please help me on this.

var name = dt1.AsEnumerable()
    .Where(p => (int)p["Age"] >= 29)
    .GroupBy(p =>p.Field<string>("Role"))
    .Select(p => new{ID = p.Field<int>("ID"),Name =p.Field<string>("Name"),Role = p.Field<string>("Role"),Age = p.Field<int("Age")});

Upvotes: 2

Views: 619

Answers (2)

Raghu
Raghu

Reputation: 136

Refer LINQ Case statement with COUNT and GROUP for selecting fields in group by. both Lambda exp and c# linq is available.

Upvotes: 0

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11478

Correct code:

var name = dt1.AsEnumerable()
                  .Where(p => p.Field<int>("Age") >= 29)
                  .GroupBy(p =>p.Field<string>("Role"))
                  .Select(q => q.Select(p => new{ID = p.Field<int>("ID"),Name =p.Field<string>("Name"),Role = p.Field<string>("Role"),Age = p.Field<int>("Age")}));

Explanation:

  • GroupBy will create IEnumerable<IGrouping<string,DataRow>> in this case
  • When you do Select, you get IGrouping, on which you need to do further Select to get the exact element DataRow used for creation of result Anonymous Type as in this case

Upvotes: 1

Related Questions