2017-07-26 63 views
1

我已經使用LINQ內部連接合並了2個表客戶端和付款。在此之後,我用這兩個表中的值填寫一個新模型「總計」。我只需要獲得Username。有任何想法嗎?我會非常感謝!如何使用linq在選擇查詢中獲取值?

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

回答

3

按鍵和名稱分組。您可以通過使用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(); 
+0

它幫了我很多。我的讚賞! –

+0

請接受答案,以向其他人展示這是有幫助的,並得到了答覆。 –

+0

當然,但時間限制還沒有結束標記您的答覆作爲答案;) –