C# 如何从集合中检索第一项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/587351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I retrieve first item from a Collection?
提问by Jonathan Escobedo
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
但不起作用的原因和显式转换已经存在
采纳答案by lc.
Why not just use var?
为什么不直接使用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.
至于您收到错误的原因,我猜测 Key 或 Element 与您认为的不同。查看错误消息的其余部分,了解编译器抱怨的类型。请注意,如果涉及匿名类型,则获取它的唯一方法是使用var.
回答by Jonathan Escobedo
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;
}
}
回答by Orion Edwards
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
}

