C# 代码>为了利用ForEach(…)让我不寒而栗。为什么不改用foreach循环呢?带有LazyEvaluation,不分配额外的内存(ToList数组) b.Where(v => v.P == x).ForEach(v => v.P = y);

C# 代码>为了利用ForEach(…)让我不寒而栗。为什么不改用foreach循环呢?带有LazyEvaluation,不分配额外的内存(ToList数组) b.Where(v => v.P == x).ForEach(v => v.P = y);,c#,generics,interface,dry,C#,Generics,Interface,Dry,代码>为了利用ForEach(…)让我不寒而栗。为什么不改用foreach循环呢?带有LazyEvaluation,不分配额外的内存(ToList数组) b.Where(v => v.P == x).ForEach(v => v.P = y); c.Where(v => v.P == x).ForEach(v => v.P = y); class Program { static void Main(string[] args) { in

代码>为了利用
ForEach(…)
让我不寒而栗。为什么不改用
foreach
循环呢?带有LazyEvaluation,不分配额外的内存(ToList数组)
b.Where(v => v.P == x).ForEach(v => v.P = y);
c.Where(v => v.P == x).ForEach(v => v.P = y);
class Program
{
    static void Main(string[] args)
    {
        int x = 1;
        int y = 2;

        var b = new MyCustomList<B>();

        b.Foo(v => v.P == x, n => n.P = y);
    }
}

public static class Extensions
{
    public static void Foo<T>(this IFoo<T> @this, Func<T, bool> predicate, Action<T> action) => @this.Where(predicate).ToList().ForEach(action);
}

public interface IFoo<T> : IList<T>  { }

class MyCustomList<T> : List<T>, IFoo<T>  { }

class B
{
    public int P { get; set; }
}
public interface IHasPropertyP { Foo P { get; } }
public class B: D, IHasPropertyP { ... }
public class C: D, IHasPropertyP { ... }

List<D> dees = ... //I don't care if the type of the items is B, C or D
var onlyThoseWhoHavePropertyP = dees.OfType<IHasPropertyP>();
onlyThoseWhoHavePropertyP.Where(v => v.P == x).{whatever needs to be done...}