C#扩展foreach,可以传入action

C#扩展foreach,可以传入action

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
}

示例:

1
2
3
4
5
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));
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×