HelloWorld1
HelloWorld1

Reputation: 14108

Merge duplicate data without affecting others in LINQ code

Goal:
If any duplicate, it should be merged into one for instance if "_name: a", _quantity: 3" and "_name: a", _quantity: 6" should be merged into "_name: a", _quantity: 9" in the list with other data with duplicate or not.

Problem: I have a list with lots of data and I don't know how to merge duplicate data into one unit + it should not affect others. If possible, would like everyting to be happened inte same list without creating more list to acheive the result.

List<Sale> myList = GetAllSalesList()


public classs Sale
{
     public string _name;
     public string _quantity;
}

Upvotes: 5

Views: 3657

Answers (3)

Stuart
Stuart

Reputation: 66882

You could do this by using Grouping

var query = from sales in list
            group sale by _name into grouped
            select new Sale
            {
               _name = grouped.Key,
               _quantity = grouped.Sum(x => x._quantity)
            }; 

var groupedList = query.ToList();

For more on grouping, please see the practical examples in the 101 page - http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

Note - this answer assumes that _quantity is actually an int and that integer overflow is not a concern

Upvotes: 2

digEmAll
digEmAll

Reputation: 57210

Something like this ?

var mergedList = 
myList.GroupBy(x => x._name)
      .Select(g => new Sale{_name = g.Key, _quantity = g.Sum(x => x._quantity)})
      .ToList();

EDIT:

I've just noticed that _quantity is a string, is that correct ?
If it is, change the piece of code using Sum(), to:

g.Sum(x => int.Parse(x._quantity)).ToString()

of course if _quantity represents an int... otherwise use double or decimal etc...

Upvotes: 5

Bala R
Bala R

Reputation: 108937

var aggregateList = 
    myList.GroupBy(i => i._name)
          .Select(g => new Sale
         {
             _name = g.Key, 
             _quantity = g.Sum(x => Convert.ToInt64(x._quantity)).ToString()
         })
         .ToList();

Upvotes: 0

Related Questions