我正在尝试通过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);
最佳答案
我猜您正在使用某种ORM库,而EDC.Energideklarationer_As
对象是在该ORM中实现的IQueryable
。发生的情况是该库试图从LINQ查询生成对基础数据源的查询(也许是SQL查询,具体取决于您所使用的库)。
某些ORM不支持某些表达式-例如,实体框架将不处理select new int[] { ... }
,但将处理select new List<int> { ... }
。您正在使用的库似乎不支持在查询中创建新的列表。并在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")
}