2009-02-25 52 views
2

我不知道如何从这个集合中检索的第一个项目:如何从集合中检索第一个项目?

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

我也tryed:

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

而不是作品引起和显式转换已经存在

+0

你能发布你在第一用得到“组”的查询地点? – 2009-02-25 19:16:10

回答

6

为什么不直接使用var

var firstFromGroup = group.First(); 

至于你得到一个错误的原因,我猜测Key或Element与你认为的不同。看看错误消息的其余部分,看看编译器在抱怨什么类型。请注意,如果涉及到匿名类型,唯一的方法是使用var

+0

原因我使用两个foreachs从每一行传递数据.. – 2009-02-25 19:22:08

0

这是我的部分解决方案:

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; 
        } 
       } 
1

试试这个(根据你的部分解决方案):

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 
} 
+0

从一个var的内存成本是多少?匿名类型比知道类型更重? – 2009-02-25 20:04:12

相关问题