Linq表示不同地址之和

本文关键字:地址 表示 Linq | 更新日期: 2023-09-27 18:04:40

我有一个产品的DataTable。每个产品都有重量和退货地址。返回地址由7个字段组成。

我需要循环遍历不同的地址并求和product的总重量

示例表如下所示:

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?或者在DataTable上用SqlDataAdaptor会更好吗?我知道如何使用SqlDataAdaptor,但我不知道如何使用Linq,我猜Linq会更好的开销?

Linq表示不同地址之和

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

按所有地址字段对表行进行分组,并计算每组的和:

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属性中包含权重之和。