djedjica
djedjica

Reputation: 125

LINQ compare lists and update property with values from found object

I have 2 lists with same object type(Lets say list A and B). Object has property amount. Is there way with using linq to compare first list with second one and when object from list A is found in list B (by ID), update object's, in list A, amount and set it be old value minus amount of object in list B.

  List A                         List B                     Result list
    ID  Name      Amount        ID  Name   Amount      ID   Name    Amount
    5   obj1       5            5   obj1    1           5    obj1    4
    9   obj2       4            9   obj2    2           9    obj2    2
    16  obj3       3            16  obj3    3           16   obj3    0

Kind regards,

Upvotes: 0

Views: 234

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460038

I would use a join:

var query = from a in ListA join b in ListB on a.ID equals b.ID
            select new{ A = a, NewValue = a.Amount - b.Amount };
foreach(var x in query)
    x.A.Amount = x.NewValue;

This is more efficient since Join uses a set based approach and also only updates if necessary.

Upvotes: 2

Daniele Sartori
Daniele Sartori

Reputation: 1703

i would go for a simple loop since i find it more readable in these cases (personal opinion)

foreach(MyObj o in A)
{
   IEnumerable<MyObj> supp = B.Where(b => b.Name == o.Name);
   if(supp != null)
   {
     foreach(MyObj ob in supp)
     {
       o.Amount -= ob.Amount;
     }
   }
}

Upvotes: 0

Onyx Caldin
Onyx Caldin

Reputation: 299

listA.ForEach(obj => 
{
    obj.Amount -= listB.SingleOrDefault(other => obj.Id == other.Id)?.Amount ?? 0;
}

This iterates over listA and substracts listB corresponding Amount if there's one, substracts 0 otherwise (do nothing).

Upvotes: 3

Related Questions