我有DataTable
个产品。每个产品都有一个重量和一个返回地址。
返回地址由7个字段组成。
我需要遍历不同的地址并总结产品的总重量。
示例表看起来像这样......
Product weight address1 address2 address3 city state postcode country
A123 6 House 1st Street some place a city a state AB1 2CD GB
A456 3 House 1st Street some place a city a state AB1 2CD GB
A789 4 House 1st Street some place a city a state AB1 2CD GB
A123 6 House2 2st Street another place another city another state EF2 3GH GB
A456 3 House2 2st Street another place another city another state EF2 3GH GB
A789 4 House2 2st Street another place another city another state EF2 3GH GB
我会有2个地址返回13的权重。
我只需要按地址字段(不是产品)分组,并按地址加权。我还需要返回国家以及总重量。
使用linq可以吗?或者我会更好地使用SqlDataAdaptor
上的DataTable
?
我知道如何处理SqlDataAdaptor
,但我不知道如何处理Linq,我猜测linq对开销更好?
答案 0 :(得分:3)
GroupBy()
会将所有产品分组到每个不同地址的子集合中。
然后Select()
总计每个子集合的权重以提供总权重。
var totals = products
.GroupBy(p => new
{
address1 = p.Field<string>("address1"),
address2 = p.Field<string>("address2"),
address3 = p.Field<string>("address3"),
city = p.Field<string>("city"),
state = p.Field<string>("state"),
postcode = p.Field<string>("postcode"),
country = p.Field<string>("country")
})
.Select(g => new
{
Total = g.Sum(p => p.Field<int>("weight"),
Country = g.Key.country
});
使用示例:
foreach (var address in totals)
{
Console.WriteLine(string.Format("Country: {0}, Weight: {1}", address.Country, address.Total));
}
答案 1 :(得分:2)
按所有地址字段对表行进行分组,以及每个组的计算总和:
var query =
from p in table.AsEnumerable()
group p by new {
Address1 = p.Field<string>("address1"),
Address2 = p.Field<string>("address2"),
Address3 = p.Field<string>("address3"),
City = p.Field<string>("city"),
State = p.Field<string>("state"),
Postcode = p.Field<string>("postcode"),
Country = p.Field<string>("country")
} into g
select new {
Address = g.Key,
TotalWeight = g.Sum(x => x.Field<int>("weight"))
};
这将为您提供一系列匿名对象,其中包含Address属性中的所有地址字段和TotalWeight属性中的权重总和。