使用Linq和Lambda表达式在列表中执行计算

本文关键字:列表 执行 计算 表达式 Linq Lambda 使用 | 更新日期: 2023-09-27 17:52:54

我有以下对象:

public class Foo
{
    public Int32 Id 
    public Int32 SampleId 
    public Int32 CompanyId 
    public Decimal Data 
}
public class Bar
{
    public Int32 CompanyId 
    public Decimal Data  
}

我有这些对象的列表。我想执行一个计算,首先按"CompanyId"对id进行分组。然后,为每个公司ID添加3个不同的SampleIds Data,并为每个公司返回一个新对象。

//I want to get the data from SampleId = 2, 4 and 6 added together 
//from the Foo object and put into the Data of the new Bar object.
List.GroupBy(l => l.CompanyId).Select( x => new Bar { CompanyId = x.Key, ????? } );

我被如何在分组后执行计算所困扰。

使用Linq和Lambda表达式在列表中执行计算

你看起来离我很近。

这个应该可以工作:

    var list = new List<Foo>
                   {
                       new Foo { CompanyId = 1, Data = 15, Id = 1, SampleId = 2 },
                       new Foo { CompanyId = 1, Data = 10, Id = 2, SampleId = 4 },
                       new Foo { CompanyId = 1, Data = 25, Id = 2, SampleId = 6 }
                   };
    var output = list.GroupBy(
        l => l.CompanyId,
        (key, data) => new Bar { CompanyId = key, Data = data.Sum(d => d.Data) });

或者如果你想过滤掉2,4,6作为样本id(不能说我理解为什么要说实话),那么这可以工作:

[Test]
public void Testing()
{
    var list = new List<Foo>
                   {
                       new Foo { CompanyId = 1, Data = 15, Id = 1, SampleId = 2 },
                       new Foo { CompanyId = 1, Data = 10, Id = 2, SampleId = 4 },
                       new Foo { CompanyId = 1, Data = 25, Id = 3, SampleId = 8 },
                       new Foo { CompanyId = 1, Data = 25, Id = 4, SampleId = 12 },
                       new Foo { CompanyId = 1, Data = 25, Id = 5, SampleId = 14 }
                   };
    var filterList = new List<int> { 2, 4, 6 };
    var output = list.Where(l => filterList.Contains(l.SampleId))
        .GroupBy(l => l.CompanyId, (key, data) => new Bar { CompanyId = key, Data = data.Sum(d => d.Data) });
    Assert.True(output != null);
    Assert.True(output.FirstOrDefault() != null);
    Assert.True(output.FirstOrDefault().Data == 25);
}