简体   繁体   English

如何使用linq在select查询中获取值?

[英]How can I get a value inside the select query using linq?

I have combined 2 tables Clients and Payments using LINQ inner join. 我使用LINQ内连接组合了2个表客户端和付款。 After this, I fill in a new model Totals with a values from those two tables. 在此之后,我用这两个表中的值填写一个新模型Totals。 I just need to get a Username . 我只需要获得一个Username Any ideas? 有任何想法吗? I'll be very thankful! 我会非常感激的!

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();

Group by key and name. 按键和名称分组。 You can group by mutiple columns by creating new anonymous object with new {id,name} . 您可以通过使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM