Home > Enterprise >  LINQ - Count and sum duplicates in List<Tuple<int, double>>
LINQ - Count and sum duplicates in List<Tuple<int, double>>

Time:12-08

Since I havent't used LINQ much, the following is a hard task for me: Having a list like List<Tuple<int, double>> I want to receive a List containing the amount (count) of duplicates of Item(1) and the corresponding sum of Item(2). The list should be orderd descending by the count of duplicates. How would a LINQ look like to get the result?

Thank you in advance. Rafael

CodePudding user response:

@JonasH explained the concept to achieve the result.

With these steps:

  1. Group by Item1.
  2. Perform count for grouped key and sum for total Item2.
  3. Find duplicate Item1 with Count is greater than 1.
  4. Order by Count descending.
var result = input.GroupBy(x => x.Item1)
            .Select(x => new
                    {
                        Item = x.Key,
                        Count = x.Count(),
                        Sum = x.Sum(y => y.Item2)
                    })
            .Where(x => x.Count > 1)
            .OrderBy(x => x.Count)
            .ToList();

enter image description here

Result enter image description here

  • Related