删除重复的行

时间:2013-03-22 12:07:41

标签: c# linq

首先,我将发布到目前为止我所做的事情:

from person in Persons
join customer in Customers on person.BusinessEntityID equals customer.PersonID
join salesOrderHeader in SalesOrderHeaders on customer.CustomerID equals salesOrderHeader.CustomerID
where salesOrderHeader.SubTotal > 1000
join address in Addresses on salesOrderHeader.BillToAddressID equals address.AddressID
where address.City == "Melton"
select new {
                person.FirstName,
                person.LastName,
                salesOrderHeader.SubTotal,
            address.City
       }

此查询完美地解决了问题,即我在firstnamelastname上找回了重复的行。我可以通过添加已尝试过的Distinct()扩展方法来解决这个问题,但是如果可以在没有任何扩展方法的情况下完成,我会非常好奇。

那么如何在firstnamelastname上没有任何重复行的情况下返回结果表?

编辑:在这种情况下,我收回了类似的内容:

enter image description here

我想只回来一个相同类型的人,并且他花费了总价值。因为没有更好地解释自己,第一次忘记提及我想要取回该人的总价值< / p>

1 个答案:

答案 0 :(得分:1)

您需要的是GroupBy和聚合。

from person in Persons
join customer in Customers on person.BusinessEntityID equals customer.PersonID
join salesOrderHeader in SalesOrderHeaders on customer.CustomerID equals salesOrderHeader.CustomerID
where salesOrderHeader.SubTotal > 1000
join address in Addresses on salesOrderHeader.BillToAddressID equals address.AddressID
where address.City == "Melton"
group salesOrderHeader by new { person.FirstName, person.LastName } into g //new
select new {
                g.Key.FirstName,
                g.Key.LastName,
                SubTotal = g.Sum(salesOrderHeader => salesOrderHeader.SubTotal),
            address.City
       }

GroupBy将多行折叠成一行,这就是你想要的。