Theun Arbeider
Theun Arbeider

Reputation: 5409

How to create extension method taking lambda expression

Greetings,

I'm looking for a way to convert

foreach (var sEvent in Events)
{
    sEvent.SomeId = 0;
}

to

Events.Set(m=>m.SomeId, 0); 

or something like this.

So basicly I want to make it a one line event that sets all "SomeId" to 0;

Is there any way?

Upvotes: 2

Views: 1275

Answers (4)

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

If Events is a List<T> you can use:

Events.ForEach( m => m.SomeId = 0 );

If Events is IEnumerable, ForEach is not implemented, but you can of course make your own ForEach that works on IEnumerable yourself. The reason ForEach is not created for IEnumerable, is that they did not want to have extension method on IEnumerable with side effects (that altered the original collection).

Implementing ForEach on IEnumerable is easy enough:

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
  foreach (T element in source) 
    action(element);
  return source;
}

This has to go into a static class just like all other extension methods.

Upvotes: 6

Jason
Jason

Reputation: 1015

If Events is a List, you could do:

Events.ForEach(m => m.SomeId = 0);

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

If Events is a List<T> you can simply use

Events.ForEach(e => e.SomeId = 0);

Upvotes: 2

Anuraj
Anuraj

Reputation: 19598

You can do this

Events.ToList().ForEach(Event => Event.SomeId = 0);

Upvotes: 2

Related Questions