views:

373

answers:

3

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

+4  A: 

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.

lc
cause Im was using two foreachs for pass data from each row..
Angel Escobedo
A: 

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;
                    }
                }
Angel Escobedo
A: 

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
}
Orion Edwards
How much is the memory cost from a var? also anonymous types are more heaviest than a knowed type?
Angel Escobedo
A var is free. when you do var x = "x"; the compiler can see that "x" is a string, and so it writes String x = "x"; It all happens in the compiler, and the code that comes out in your .EXE file will be identical
Orion Edwards