Camille Sévigny
Camille Sévigny

Reputation: 5143

Perform Calculations Within List Using Linq and Lambda Expressions

I have the following object:

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

public class Bar
{
    public Int32 CompanyId 
    public Decimal Data  
}

I have a list of these objects. I want to perform a calculation where I group the Ids by "CompanyId" first. Then for each company ID, add 3 different SampleIds Data together and returning a new object for each company.

//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, ????? } );

I am stuck with how to perform the calculation after I do the grouping. Any help is much appreciated.

Upvotes: 0

Views: 702

Answers (1)

OCDan
OCDan

Reputation: 1153

You look to be pretty close to me.

This should work:

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

Or if you want to filter out just 2,4,6 as sample id (can't say I understand why to be honest) then this could work:

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

Upvotes: 2

Related Questions