开发者

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

开发者 https://www.devze.com 2023-01-21 10:44 出处:网络
I have a collection of Obj\'s, I want to go through the collection, and set a property if a condition is true, so in normal world it would be:

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

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

Anyway to do this, us开发者_开发问答ing Linq, to make it in a single line?


LINQ isn't all that useful for executing side effects, it's primarily intended for querying. In truth, the fact that it has deferred execution so engrained in its behaviour makes it a poor choice for executing side-effects, IMO.

The code you've got looks perfectly fine to me. If you did want to use LINQ though, I doubt you could improve much on:

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

Now, that isn't all that better (arguably worse) than your original.

On the other hand, if you wanted to create a new, streaming sequence with projections of the original items having the desired characteristics, you could do something like:

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

EDIT: If you don't want to heed the advice of the experts (read: Eric Lippert), you can write your own extension-method:

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);
}

This will allow you to do:

obj.Where(o => o.SomeProperty == Something)
   .Do(o => o.SomeOtherProperty = true);


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


Using an 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();
}

Usage:

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

精彩评论

暂无评论...
验证码 换一张
取 消