【问题标题】:Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'int'参数 1:无法从 'System.Collections.Generic.IEnumerable<AnonymousType#1>' 转换为 'int'
【发布时间】:2014-04-20 07:08:03
【问题描述】:

我对 linq 问题中的方法 Count() 有疑问:

IEnumerable<BookListRecord> bookListRecord;

IEnumerable<Tuple<string, int>> listTeacher = new List<Tuple<string, int>>(
from b in bookListRecord
group b by b.Teacher into g
select new { g.Key, Count = g.Count()}
);

我收到错误:参数 1:无法从 'System.Collections.Generic.IEnumerable&lt;AnonymousType#1&gt;' 转换为 'int'

当我使用时:

select new {g.Key, g.Count()}

我收到错误:无效的匿名类型成员声明符。必须使用成员分配、简单名称或成员访问来声明匿名类型成员。

请问如何将记录数与 listTeacher 相匹配?谢谢你的回答。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    问题是您将变量键入为IEnumerable&lt;Tuple&lt;string, int&gt;&gt;,但您正在使用select new {g.Key, g.Count()} 创建一个匿名类型。将其更改为以下内容。

    IEnumerable<Tuple<string, int>> listTeacher = 
                                             (from b in bookListRecord
                                              group b by b.Teacher into g
                                              select Tuple.Create( g.Key, g.Count()))
                                             .ToList()
    

    【讨论】:

    • 您忘记删除Tuple 前面的new 关键字。另一种方法是保留匿名类型,然后将var(隐式类型)用于listTeacher。你需要(...).ToList() 而不是new List&lt;...&gt;(...)
    • @JeppeStigNielsen 谢谢,已更新。我希望现在一切都好。顺便说一句,技术上ToList 和新的List&lt;T&gt;(IEnumerable) 是相同的。
    • 是的,它们是一样的。我的意思是如果你保留匿名类型,你可以做(from b in bookListRecord group b by b.Teacher into g select new { g.Key, Count = g.Count(), }).ToList(),因为可以推断方法的类型参数(推断ToList&lt;TSource&gt; 方法中的TSource)。对于匿名类型,您不能使用 new List&lt;XXX&gt;(...),因为对于 new-object-creation 表达式,无法推断类型参数 XXX(从 C# 5 开始)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 2015-06-12
    • 1970-01-01
    • 2011-05-14
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多