Chưa phân loại

C# Tutorial – ForEach extension method

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> array, Action<T> act)
{
foreach (var i in array)
act(i);
return array;
}

public static IEnumerable<T> ForEach<T>(this IEnumerable arr, Action<T> act)
{
return arr.Cast<T>().ForEach<T>(act);
}

public static IEnumerable<RT> ForEach<T, RT>(this IEnumerable<T> array, Func<T, RT> func)
{
var list = new List<RT>();
foreach (var i in array)
{
var obj = func(i);
if (obj != null)
list.Add(obj);
}
return list;
}

Example:

string[] names = new string[] { "C#", "Java" };
names.ForEach(i => Console.WriteLine(i));

IEnumerable<int> namesLen = names.ForEach(i => i.Length);
namesLen.ForEach(i => Console.WriteLine(i));

From extensionmethod.net

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s