mo_maat
mo_maat

Reputation: 2250

How do I group by using anonymous type

I am getting a result set from a linq query and then using group by to group on two fields:

var dataElements = dataElements.GetAll();

var dataItems = dataElements.Where(el => el.Field1 == "DATE")
     .GroupBy(x => new { x.Field2, x.Field3})
     .ToList();

//why can't I do this:
foreach (var element in dataItems)
{
    Console.WriteLine(element.Field2)
}

I get the following error:

Severity Code Description Project File Line Suppression State Error CS1061 'IGrouping<, dataElements>' does not contain a definition for 'Field2' and no accessible extension method 'Field2' accepting a first argument of type 'IGrouping<, dataElements>' could be found (are you missing a using directive or an assembly reference?) App.Program C:.....cs 498 Active

Upvotes: 2

Views: 1468

Answers (3)

Mehrdad Dowlatabadi
Mehrdad Dowlatabadi

Reputation: 1335

You need to select fields before access them:

var dataItems = dataElements.Where(el => el.Field1 == "DATE")
 .GroupBy(x => new { x.Field2, x.Field3})
 .Select(x=>new {Field2=x.FirstOrDefault().Field2})
 .ToList();

now you can access Field2 :

foreach (var element in dataItems)
{
  Console.WriteLine(element.Field2)
}

Alternatively you can do it in your for loop:

foreach (var group in dataItems)
{
  foreach(var item in group)
     Console.WriteLine(item.Field2);
}

Upvotes: 3

Johnny
Johnny

Reputation: 9529

As it says group doesn't know what Field2 is so you need to grab each element of the group. Try this:

foreach (var group in dataItems) 
{ 
    foreach(var element in group)
    {
        Console.WriteLine(element.Field2);
    }
}

It can be done because dataItem itself has Field2. This will iterate through each element of each group. If you want to show only the keys of the groups then just grab key:

foreach (var group in dataItems) 
{
     Console.WriteLine(group.Key.Field2);
}

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117175

You need to select the Key first before Field2. Try this:

foreach (var element in dataItems)
{
    Console.WriteLine(element.Key.Field2)
}

Upvotes: 3

Related Questions