0

我有一个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吗?或者我会更好地使用 aSqlDataAdaptorDataTable?我知道如何处理,SqlDataAdaptor但我不知道如何处理 Linq,我猜 linq 会更好地处理开销?

4

2 回答 2

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));
}
于 2013-03-18T10:30:16.747 回答
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 属性中具有权重总和。

于 2013-03-18T10:29:34.067 回答