C# 如何从集合中检索第一项?

C# 如何从集合中检索第一项?,c#,collections,c#-3.0,C#,Collections,C# 3.0,我不知道如何从此集合中检索第一项: IGrouping<string, Plantilla> groupCast = group as System.Linq.IGrouping<string, Plantilla>; IGrouping groupCast=group as System.Linq.IGrouping; 我还尝试: IGrouping<string, Plantilla> firstFromGroup = groupCast.FirstO

我不知道如何从此集合中检索第一项:

IGrouping<string, Plantilla> groupCast = group as System.Linq.IGrouping<string, Plantilla>;
IGrouping groupCast=group as System.Linq.IGrouping;
我还尝试:

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

但不工作原因和显式转换已经存在

为什么不直接使用
var

var firstFromGroup = group.First();

至于出现错误的原因,我猜键或元素与您认为的不同。查看错误消息的其余部分,查看编译器抱怨的类型。请注意,如果涉及匿名类型,获取它的唯一方法是使用
var

这是我的部分解决方案:

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;
                    }
                }
foreach(dlstPlantillas.SelectedItems中的var组)
{
IGrouping groupCast=组为System.Linq.IGrouping;
if(null==groupCast)返回;
foreach(groupCast.Take(1)中的Plantilla项)//适合我
{
template.codigoestudio=item.codigoestudio;
template.codigoequipo=item.codigoequipo;
template.codigoplantilla=item.codigoplantilla;
template.consummation=item.consummation;
template.hallazgo=item.hallazgo;
template.nombreequipo=item.nombreequipo;
template.nombreexamen=item.nombreexamen;
template.tecnica=item.tecnica;
}
}
试试这个(根据您的部分解决方案):

foreach(dlstPlantillas.SelectedItems中的var组)
{
var groupCast=groupCast=group as System.Linq.IGrouping
if(groupCast==null)返回;
item=groupCast.FirstOrDefault();
如果(item==null)返回;
//处理物品
}

您能否首先发布用于获取“组”的查询?var的内存成本是多少?此外,匿名类型比已知类型更重?var是免费的。当您执行var x=“x”;编译器可以看到“x”是一个字符串,因此它写入字符串x=“x”;这一切都发生在编译器中,在.EXE文件中产生的代码将是相同的,“System.Collections.Generic.HashSet”不包含“First”的定义@alamnaryab您可能忘记了包含
System.Linq
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
}