gpt4 book ai didi

c# - 按结果将 Linq 组映射到对象

转载 作者:行者123 更新时间:2023-11-30 19:11:05 27 4
gpt4 key购买 nike

我有一个充当摘要的类,它将作为 IEnumerable 传递给 MVC View 。该类看起来像:

public class FixedLineSummary
{
public long? CustomerId { get; set; }
public string CustomerName { get; set; }
public int? NumberOfLines { get; set; }
public string SiteName { get; set; }
}

从数据库返回的结果包含所有单个条目,因此我使用 linq 来总结这些:

var summary = (from r in result 
let k = new {r.CustomerId, CustomerName = r.CompanyName, r.SiteName}
group r by k into t
select new
{
t.Key.CustomerId,
t.Key.CustomerName,
t.Key.SiteName,
Lines = t.Sum(r => r.lines)
});

当我尝试将结果转换到我的对象中时,我总是收到一个错误:

Instance argument: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<Domain.Entities.FixedLineSummary>'

有没有办法将 linq 查询的结果转换为我的类的可枚举?

最佳答案

您应该更改投影以创建您的类,而不是匿名类型:

var summary = from r in result 
let k = new {r.CustomerId, CustomerName = r.CompanyName, r.SiteName}
group r by k into t
select new FixedLineSummary
{
CustomerId = t.Key.CustomerId,
CustomerName = t.Key.CustomerName,
SiteName = t.Key.SiteName,
NumberOfLines = t.Sum(r => r.lines)
};

关于c# - 按结果将 Linq 组映射到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13418815/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com