Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a foreach lambda expression on ObservableCollection<T>?

How do I execute a foreach lambda expression on ObservableCollection<T>?

There is not method of foreach with ObservableCollection<T> although this method exists with List<T>.

Is there any extension method available?

like image 318
Zain Shaikh Avatar asked Mar 25 '10 21:03

Zain Shaikh


3 Answers

There is no method available by default in the BCL but it's straight forward to write an extension method which has the same behavior (argument checking omitted for brevity)

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

Use case

ObservableCollection<Student> col = ...;
col.ForEach(x => Console.WriteLine(x.Name));
like image 159
JaredPar Avatar answered Oct 08 '22 23:10

JaredPar


public static class EnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
    {
        foreach (var e in enumerable)
        {
            action(e);
        }
    }
}
like image 40
PL. Avatar answered Oct 09 '22 00:10

PL.


observableCollection.ToList().ForEach( item => /* do something */);
like image 38
yu yang Jian Avatar answered Oct 08 '22 22:10

yu yang Jian