Update all but one in the collection using Linq

Is there a way to do the following with 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 over each object in the collection and then update the property for each object, except for one element of my collection, which should be updated to a different value.

At this point, I am using a counter to verify that I am setting my value to one and only one element of my collection. I removed it from this example so that people offer other solutions.

The original question, without exception, in the collection here

EDIT

I ask this question because I'm not sure if this can be done with LinQ. so your answers reassure my opinion of LinQ. Thank.

+5
source share
6 answers

.ForEach, , .Single, , :

// 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);
+7

Linq. ? Linq , . , , . foreach foreach. .

, :

foreach (var c in collection)
{
    c.PropertyToSet = (c.Condition == condition) ? value : otherValue;
}
+5
collection.Where(x => <condition>).ToList().ForEach(x => <action>);
+2

LINQ, :

var result = collection.Select(c =>
{
    c.PropertyToSet = c.Condition == condition ? value : otherValue;
    return c;
});

, , , :

foreach (var c in collection)
   c.PropertyToSet = c.Condition == condition ? value : otherValue;
+2

linq:

    collection.ToList().ForEach(c => c.PropertyToSet = c.Condition == condition ? value : otherValue);

However, I just use the usual foreach here to avoid converting the collection to a list.

+2
source

Well, you could do:

var itemToSetValue = collection.FirstOrDefault(c => c.Condition == condition);

if(itemToSetValue != null)
     itemToSetValue.PropertyToSet = value;

// Depending on what you mean, this predicate 
// might be c => c != itemToSetValue instead.
foreach (var otherItem in collection.Where(c => c.Condition != condition))
{
    otherItem.PropertyToSet = otherValue;
}

Now, of course, this is not a pure LINQ solution, but pure LINQ solutions are not suitable for modifying existing collections.

0
source

All Articles