c# - 如何使用 linq 在选择查询中获取值?

标签 c# asp.net linq

我使用 LINQ 内部联接合并了 2 个表 Clients 和 Payments。在此之后,我用这两个表中的值填充一个新模型 Totals。我只需要获取一个用户名。有任何想法吗?我将非常感激!

var results = from client in _db.Clients
                          join trade in _db.Payments on client.Id equals trade.ClientId
                          where (client.Id == trade.ClientId &&
                          DateTime.Compare(trade.TradeDate, (DateTime)fromDate) >= 0 &&
                          DateTime.Compare(trade.TradeDate, (DateTime) toDate) <= 0)
                          select new { client.Username, trade};
            var cs = results
                .GroupBy(tr => tr.trade.ClientId)
                .Select(item => new Totals
                {
                    Username = //here I need to set a value
                    CommBcf = item.Sum(client => client.trade.CommBcf),
                    EcnAll = item.Sum(client => client.trade.EcnAll),
                    EcnRbt = item.Sum(client => client.trade.EcnRbt),
                    OpenGross = item.Sum(client => client.trade.OpenGross),
                    CloseGross = item.Sum(client => client.trade.CloseGross)
}).ToList();

最佳答案

按键和名称分组。您可以通过使用 new {id,name} 创建新的匿名对象来按多列分组。

 var results = from client in _db.Clients
                              join trade in _db.Payments on client.Id equals trade.ClientId
                              where (client.Id == trade.ClientId &&
                              DateTime.Compare(trade.TradeDate, (DateTime)fromDate) >= 0 &&
                              DateTime.Compare(trade.TradeDate, (DateTime) toDate) <= 0)
                              select new { client.Username, trade};
                var cs = results
                    .GroupBy(tr => new {id=tr.trade.ClientId,name=tr.trade.Name})
                    .Select(item => new Totals
                    {
                        Username = item.Key.name
                        CommBcf = item.Sum(client => client.trade.CommBcf),
                        EcnAll = item.Sum(client => client.trade.EcnAll),
                        EcnRbt = item.Sum(client => client.trade.EcnRbt),
                        OpenGross = item.Sum(client => client.trade.OpenGross),
                        CloseGross = item.Sum(client => client.trade.CloseGross)
    }).ToList();

关于c# - 如何使用 linq 在选择查询中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45338015/

相关文章:

javascript - 如何在外部 javascript 文件中获取 asp.net 客户端 ID

c# - 中高级 LINQ/ Entity Framework 查询问题。标记项目

c# - IEnumerable 到参数数组

c# - Unity 5 中的构建错误

c# - 从DateTime的列表中找到最高的DateTime

c# - FluentMigrator 未运行迁移

linq - 复杂的 LINQ 或 EF 查询

c# - 如何防止用户共享同一帐户? (ASP.NET MVC)

ASP.NET MVC5 : Unobtrusive validation during the filling out of the form field

asp.net - .NET Core RC2 applicationhost.config 与 ASP.NET .NET 4.6 不兼容?