Ale
Ale

Reputation: 71

Selection of different value and conversion with LINQ

I have a simple selection with LINQ so structured:

var p = info.SpRicezioneSpedizioniLights
  .Where(x => x.SPEDIZIONE_STATO_GENERAZIONE == "I")
  .GroupBy(x => x.PROGRESSIVO);

foreach (var item in p)
{
        // item. Do something
}

I must to select all the row in SPRicezioneSpedizioniLights with different PROGRESSIVO and elaborate each row.

When i try to elaborate item i have this error:

'System.Linq.IGrouping' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'System.Linq.IGrouping' could be found (are you missing a using directive or an assembly reference?)

What is the best way to do what i want?

Thank you

Upvotes: 1

Views: 64

Answers (2)

Valentin
Valentin

Reputation: 5488

Not with a specific PROGRESSIVO but all the rows with the first different PROGRESSIVO

The problem is that result of GroupBy is System.Linq.IGrouping object that contains the key with a group of elements. So if you need first row from group you can use FirstOrDefault() method.

var p = info.SpRicezioneSpedizioniLights
          .Where(x => x.SPEDIZIONE_STATO_GENERAZIONE == "I")
          .GroupBy(x => x.PROGRESSIVO)
          .Select(x=>x.FirstOrDefault());

foreach(var item in p)
{
   if (item != null)
       item.SPEDIZIONE_STATO_GENERAZIONE = "G";
}  

Upvotes: 1

Aducci
Aducci

Reputation: 26664

You need to add another foreach loop to get the detail of your groups.

 foreach (var groupingLevel in p)
 {
    // groupingLevel.Key

    foreach(var item in groupingLevel)
    {
       // item. Do something
    }               
 }

Upvotes: 0

Related Questions