【问题标题】:ASP.NET LINQ Error Cannot create a query result of type 'System.Collections.Generic.List`1[System.Int32]'ASP.NET LINQ 错误无法创建类型为“System.Collections.Generic.List`1[System.Int32]”的查询结果
【发布时间】:2014-08-18 10:14:08
【问题描述】:

我正在尝试通过 Linq 语句创建 Dictionary<string, List<int>>

它给了我以下错误:无法创建类型为“System.Collections.Generic.List`1[System.Int32]”的查询结果

        var output = (
                    from e in EDC.Energideklarationer_As
                    where MunicipalityName.Contains(e.Municipality)
                    group e by e.Municipality into g
                    select new
                    {
                        Municipality = g.Key,

                        listan = new List<int>()
                        {
                        g.Count(e => e.H== "El"),
                        g.Count(e => e.H== "Eldningsolja"),
                        g.Count(e => e.H== "Flis"),
                        g.Count(e => e.H== "Markvarmepump"),
                        g.Count(e => e.H== "Ved")
                        }
                    }
            ).ToDictionary(x => x.Municipality, x=> x.listan);

【问题讨论】:

  • 您可以尝试将selectToDictionary() 分成两行,如果仍然出现错误,请告诉我们?如果是这样,请告诉我们是哪一行导致了错误。
  • 感谢您的回复。虽然不确定你的意思。你能给我举个例子吗?
  • var temp = from e in...,然后var output = temp.ToDictionary(x =&gt; x.Municipality, x=&gt; x.listan); 这样我们就可以知道您的 linq 的哪一部分真正触发了问题。
  • 它在 .ToDictionary() 处抱怨同样的错误:无法创建类型为“System.Collections.Generic.List`1[System.Int32]”的查询结果。
  • EDC.Energideklarationer_As 恰好是IQueryable

标签: c# asp.net-mvc linq dictionary


【解决方案1】:

我猜您正在使用某种 ORM 库,而 EDC.Energideklarationer_As 对象是在该 ORM 中实现的 IQueryable。发生的情况是该库正在尝试从您的 LINQ 查询生成对基础数据源的查询(可能是 SQL 查询,具体取决于您使用的库)。

某些 ORM 不支持某些表达式 - 例如,实体框架不会处理 select new int[] { ... },但会处理 select new List&lt;int&gt; { ... }。您使用的库似乎不支持在查询中创建新列表。并且在ToDictionary 中引发了异常,因为这是实例化结果并翻译 LINQ 的地方。

尝试替换列表:

                listan = new List<int>()
                {
                    g.Count(e => e.H== "El"),
                    g.Count(e => e.H== "Eldningsolja"),
                    g.Count(e => e.H== "Flis"),
                    g.Count(e => e.H== "Markvarmepump"),
                    g.Count(e => e.H== "Ved")
                }

使用另一种匿名类型:

                listan = new 
                {
                    El = g.Count(e => e.H== "El"),
                    Eldningsolja = g.Count(e => e.H== "Eldningsolja"),
                    Flis = g.Count(e => e.H== "Flis"),
                    Markvarmepump = g.Count(e => e.H== "Markvarmepump"),
                    Ved = g.Count(e => e.H== "Ved")
                }

【讨论】:

    猜你喜欢
    • 2013-10-06
    • 2012-05-22
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多