C # Linq - SET syntax from SQL, i.e. SET abc (obj property) WHERE xyz = true in IEnumerable <obj>

I have Obj's collection, I want to go through the collection and set the property if the condition is true, so in a normal world it would be:

foreach (var o in obj)
{
   if (o.SomeProperty == Something)
   {
      o.SomeOtherProperty = true;
   }
}

Anyway, using Linq to make it on one line?

+3
source share
3 answers

LINQ is not all that is useful for performing side effects; it is primarily intended for queries. In truth, the fact that he postponed a performance so rooted in his behavior makes him a poor choice for side effects, IMO.

, , . LINQ, , :

foreach (var o in obj.Where(i => i.SomeProperty == Something))
{
   o.SomeOtherProperty = true;
}  

, , (, ), .

, , , - :

var projection = obj.Where(i => i.SomeProperty == Something)
                    .Select(i => new Foo(i) { SomeOtherProperty = true });
                    // assuming your type has a copy-constructor

EDIT. (.: Eric Lippert), :

public static void Do<T>(this IEnumerable<T> source, Action<T> action)
{ 
  if (source == null)
     throw new ArgumentNullException("source");

  if (action == null)
     throw new ArgumentNullException("action");

  foreach (T item in source) 
     action(item);
}

:

obj.Where(o => o.SomeProperty == Something)
   .Do(o => o.SomeOtherProperty = true);
+5
obj.Where(i => i.SomeProperty == Something).ToList().ForEach(o => o.SomeOtherProperty = true);  
+3

Using the extension method:

public static int UpdateOnPredication<T>(this IEnumerable<T> source, Func<T, bool> predicate, Action<T> update)
{
    //check the parameters here if (source==null) ...
    var query = source.Where(predicate);
    foreach (var item in query)
    {
        update(item);
    }
    return query.Count();
}

Using:

results.UpdateOnPredication(x => x.ID > 1000, x => x.Status = 1);
+1
source

Source: https://habr.com/ru/post/1770656/


All Articles