Jonathan Escobedo
Jonathan Escobedo

Reputation: 4063

How can I retrieve first item from a Collection?

I dont know how to retrieve first Item from this collection :

IGrouping<string, Plantilla> groupCast = group as System.Linq.IGrouping<string, Plantilla>;

I also tryed :

IGrouping<string, Plantilla> firstFromGroup = groupCast.FirstOrDefault();

but not works cause and explicit conversion already exist

Upvotes: 6

Views: 32132

Answers (3)

Orion Edwards
Orion Edwards

Reputation: 123692

Try this (based on your partial solution):

foreach (var group in dlstPlantillas.SelectedItems)
{
    var groupCast = groupCast = group as System.Linq.IGrouping<string, Plantilla>
    if(groupCast == null) return;

    item = groupCast.FirstOrDefault<Plantilla>();  
    if(item == null) return;

    // do stuff with item
}

Upvotes: 1

Jonathan Escobedo
Jonathan Escobedo

Reputation: 4063

This is my partial solution :

foreach (var group in dlstPlantillas.SelectedItems)
                {
                    IGrouping<string, Plantilla> groupCast = group as System.Linq.IGrouping<string, Plantilla>;

                    if (null == groupCast) return;
                    foreach (Plantilla item in groupCast.Take<Plantilla>(1)) //works for me
                    {
                        template.codigoestudio = item.codigoestudio;
                        template.codigoequipo = item.codigoequipo;
                        template.codigoplantilla = item.codigoplantilla;
                        template.conclusion = item.conclusion;
                        template.hallazgo = item.hallazgo;
                        template.nombreequipo = item.nombreequipo;
                        template.nombreexamen = item.nombreexamen;
                        template.tecnica = item.tecnica;
                    }
                }

Upvotes: 0

lc.
lc.

Reputation: 116538

Why not just use var?

var firstFromGroup = group.First();

As for the reason you're getting an error, I'm guessing either the Key or Element is different than what you think they are. Take a look at the rest of the error message to see what types the compiler is complaining about. Note that if there is an anonymous type involved, the only way to get it is using var.

Upvotes: 13

Related Questions