代码之家  ›  专栏  ›  技术社区  ›  Stefan Steinegger

Linq样式“for each”[副本]

  •  160
  • Stefan Steinegger  · 技术社区  · 15 年前

    可能重复:
    Linq equivalent of foreach for IEnumerable

    对于“for each”操作,是否有LINQ风格的语法?

    例如,将基于一个集合的值添加到另一个已存在的集合:

    IEnumerable<int> someValues = new List<int>() { 1, 2, 3 };
    
    IList<int> list = new List<int>();
    
    someValues.ForEach(x => list.Add(x + 1));
    

    而不是

    foreach(int value in someValues)
    {
      list.Add(value + 1);
    }
    
    6 回复  |  直到 8 年前
        1
  •  229
  •   Mark Seemann    11 年前

    someValues.ToList().ForEach(x => list.Add(x + 1));
    


    System Reactive Extensions

    using System.Reactive.Linq;
    
    someValues.ToObservable().Subscribe(x => list.Add(x + 1));
    

    ToList

        2
  •  86
  •   Noldorin    15 年前

    Array List<T> ForEach static

    foreach IEnumerable<T>

    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        foreach (var item in source)
            action(item);
    }
    

        3
  •  29
  •   LukeH    14 年前

    public static void ForEach<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);
        }
    }
    
        4
  •  18
  •   stusmith    15 年前

    list.Select( x => x+1 )
    

    var someValues = new List<int>( list.Select( x => x+1 ) );
    
        5
  •  3
  •   dustyburwell    15 年前

    List

    foreach

    foreach (var x in someValues)
    {
        list.Add(x + 1);
    }
    

    public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
    {
       foreach (var x in @this)
          action(x);
    }
    
        6
  •  2
  •   R. Martinho Fernandes    15 年前