Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all objects except one in a collection using Linq

Tags:

c#

.net

linq

Is there a way to do the following using Linq:

foreach (var c in collection)
{
    if (c.Condition == condition)
    {
        c.PropertyToSet = value;
        // I must also check I only set this value to one minimum and only one element.
    }
    else
    {
        c.PropertyToSet = otherValue;
    }
}

To clarify, I want to iterate through each object in a collection and then update a property on each object except for one element of my collection that should updated to another value.

At this moment I use a counter to check I set my value to one and only one element of my collection. I removed it from this example to let people suggest other solutions.

The original question without exception in collection is here

EDIT

I ask this question because I'm not sure it's possible to do it with LinQ. so your answers comfort my opinion about LinQ. Thank you.

like image 345
Bastien Vandamme Avatar asked Mar 13 '13 15:03

Bastien Vandamme


2 Answers

You can use .ForEach to make the change, and .Single to verify only one element matches the condition:

// make sure only one item matches the condition
var singleOne = collection.Single(c => c.Condition == condition);
singleOne.PropertyToSet = value;

// update the rest of the items
var theRest = collection.Where(c => c.Condition != condition);
theRest.ToList().ForEach(c => c.PropertyToSet = otherValue);
like image 139
mellamokb Avatar answered Oct 02 '22 20:10

mellamokb


I don't suggest you to implement this with Linq. Why? Because Linq is for querying, not for modification. It can return you objects which match some condition, or objects which don't match. But for updating those objects you still need to use foreach or convert query results to list and use ForEach extension. Both will require enumerating sequence twice.

So, simple loop will do the job:

foreach (var c in collection)
{
    c.PropertyToSet = (c.Condition == condition) ? value : otherValue;
}
like image 40
Sergey Berezovskiy Avatar answered Oct 02 '22 21:10

Sergey Berezovskiy