如何在Linq中使用Var内部的数据?

时间:2014-03-26 06:32:05

标签: c# linq list asp.net-mvc-4

我想从“结果视图”中的所有数据中使用Group by对记录进行求和。

enter image description here

任何人都可以为此指导我。!

这是我的代码

var tData1 = (from i in _data.Transactions
                          join y in _data.DeviceInformations on i.DeviceInfoId equals y.DeviceInfoId
                          join u in _data.AccountDevices on y.DeviceInfoId equals u.DeviceInfoId
                          where y.Active == true && u.AccountId == 1000001 && u.Active == true
                          group i by i.DeviceInfoId into g
                          select g.OrderByDescending(t => t.DateCreated)).ToList();


foreach (var xCo in tData1)
{
   //I am getting Data in xCo
}

2 个答案:

答案 0 :(得分:1)

基于@Nayeem Mansoori解决方案,您可以试试这个。

var tData1 = (from i in _data.Transactions
                          join y in _data.DeviceInformations on i.DeviceInfoId equals y.DeviceInfoId
                          join u in _data.AccountDevices on y.DeviceInfoId equals u.DeviceInfoId
                          where y.Active == true && u.AccountId == 1000001 && u.Active == true
                          group i by i.DeviceInfoId into g
                          select new {Id = DeviceInfoId, sum = g.Sum(x=>x.DeviceInfoId)};

答案 1 :(得分:1)

请写这样你的代码,你想要列名称的总和,所以写得像这样。我想显示我使用的代码。

var results = 
from row in lDTSalesOrder
group row by new { SKU = row.Field<string>("SKU"), UnitPrice = row.Field<string>("UnitPrice") } into grp
orderby grp.Key.SKU
select new
{
    SKU = grp.Key.SKU,
    Quantity = grp.Sum(r => r.Field<double>("Quantity")),
    UnitPrice = grp.Key.UnitPrice,
    LinePrice = grp.Sum(r => r.Field<double>("LinePrice"))
};