我不知道如何从这个集合中检索第一个项目:
IGrouping<string, Plantilla> groupCast = group as System.Linq.IGrouping<string, Plantilla>;
我也尝试了:
IGrouping<string, Plantilla> firstFromGroup = groupCast.FirstOrDefault();
但不起作用,因为已经存在原因和显式转换
我不知道如何从这个集合中检索第一个项目:
IGrouping<string, Plantilla> groupCast = group as System.Linq.IGrouping<string, Plantilla>;
IGrouping<string, Plantilla> firstFromGroup = groupCast.FirstOrDefault();
但不起作用,因为已经存在原因和显式转换
为什么不直接使用 var
?
var firstFromGroup = group.First();
至于你遇到错误的原因,我猜测可能是键或元素与你想象的不同。查看错误消息的其余部分,以了解编译器抱怨的类型。请注意,如果涉及匿名类型,则唯一获取它的方法是使用var
。
尝试这个(基于你的部分解决方案):
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
}
这是我的部分解决方案:
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;
}
}