选择多个字段group by和sum



我想用linq(对象列表)做一个查询,我真的不知道该怎么做,我可以做组和和,但不能选择其余的字段。例子:

ID  Value     Name   Category
1   5         Name1  Category1  
1   7         Name1  Category1
2   1         Name2  Category2
3   6         Name3  Category3
3   2         Name3  Category3

我想按ID分组,按值求和,并返回这样的所有字段。

ID  Value     Name   Category
1   12        Name1  Category1  
2   1         Name2  Category2
3   8         Name3  Category3

更新:如果您试图避免对所有字段进行分组,您可以仅按Id:

分组。
data.GroupBy(d => d.Id)
    .Select(
        g => new
        {
            Key = g.Key,
            Value = g.Sum(s => s.Value),
            Name = g.First().Name,
            Category = g.First().Category 
        });

但是这段代码假设对于每个Id,同样的NameCategory适用。如果是这样,你应该考虑像@Aron建议的那样正常化。这意味着将IdValue保留在一个类中,并将Name, Category(以及与相同Id相同的任何其他字段)移动到另一个类中,同时还具有Id供参考。规范化过程减少了数据冗余和依赖性。

void Main()
{
            //Me being lazy in init
    var foos = new []
    {
        new Foo { Id = 1, Value = 5},
        new Foo { Id = 1, Value = 7},
        new Foo { Id = 2, Value = 1},
        new Foo { Id = 3, Value = 6},
        new Foo { Id = 3, Value = 2},
    };
    foreach(var x in foos)
    {
        x.Name = "Name" + x.Id;
        x.Category = "Category" + x.Id;
    }
            //end init.
    var result = from x in foos
                group x.Value by new { x.Id, x.Name, x.Category}
                into g
                select new { g.Key.Id, g.Key.Name, g.Key.Category, Value = g.Sum()};
    Console.WriteLine(result);
}
// Define other methods and classes here
public class Foo
{
    public int Id {get;set;}
    public int Value {get;set;}
    public string Name {get;set;}
    public string Category {get;set;}   
}

如果你的类很长,你不想复制所有的东西,你可以尝试这样做:

l.GroupBy(x => x.id).
  Select(x => {
    var ret = x.First();
    ret.value = x.Sum(xt => xt.value);
    return ret;
  }).ToList();
权力越大,责任越大。你得小心点。ret.value = x.Sum(xt => xt.value) 行将更改您的原始集合,因为您传递的是引用,而不是新对象。如果您想避免它,您需要在类中添加一些Clone方法,例如MemberwiseClone(但是,这将创建浅复制,因此要小心)。之后用var ret = x.First().Clone();
替换行

try this:

var objList = new List<SampleObject>();
objList.Add(new SampleObject() { ID = 1, Value = 5, Name = "Name1", Category = "Catergory1"});
objList.Add(new SampleObject() { ID = 1, Value = 7, Name = "Name1", Category = "Catergory1"});
objList.Add(new SampleObject() { ID = 2, Value = 1, Name = "Name2", Category = "Catergory2"});
objList.Add(new SampleObject() { ID = 3, Value = 6, Name = "Name3", Category = "Catergory3"});
objList.Add(new SampleObject() { ID = 3, Value = 2, Name = "Name3", Category = "Catergory3"});
var newList = from val in objList
              group val by new { val.ID, val.Name, val.Category } into grouped
              select new SampleObject() { ID = grouped.ID, Value = grouped.Sum(), Name = grouped.Name, Category = grouped.Category };

检查LINQPad:

newList.Dump();

相关内容

  • 没有找到相关文章

最新更新