Tom
Tom

Reputation: 1057

Combine two items in a list

I need a way to reduce a list, or calculate a "Total." I have a class, lets call it Prod. Prod contains 4 values. One is the name of the product, the id, a serial number, and a quantity. Basically I have one product but 2 different serial numbers. So when I get my data back from my query I have 2 items which I want to treat as a single item. How can I go about using LINQ or something else (I cannot foreach over them. There are many more class members and that would take a while plus look terrible). I want to be able to take the 2 instances and combine their serial numbers (not add just Serail1 - Serial 2) and also calculate the quantities together.

Upvotes: 0

Views: 2562

Answers (2)

Rob
Rob

Reputation: 1390

I think what you want is the Linq grouping function (see GroupBy - Simple 3). This should give you a list of serial numbers and their quantity count:

public void Linq42()
{
    List<Prod> products = GetProductList();

    var serialCombined =
        from p in products
        group p by p.SerialNumber into g
        select new { SerialNumber = g.Key, Total = g.Count() };
}

Upvotes: 1

Jan
Jan

Reputation: 8131

Use the join operator and place them in a Tuple. You can then call more LINQ on the tuples or iterate over them.

var combinedProducts = 
    from product1 in products1 
    join product2 in products2 on product1.serial equals product2.serial
    select Tuple.Create(product1, product2);

// Use LINQ to calculate a total    
combinedProducts.Sum(combined => combined.Item1.count * combined.Item2.price);

// Or use foreach to iterate over the tuples  
foreach (var combined in combinedProducts) {
    Console.WriteLine("{0} and {1}", combined.Item1.name, combined.Item2.name);
}

Upvotes: 0

Related Questions