110,536
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 对每个元素执行指定操作(只读)
/// </summary>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
action(item);
}
/// <summary>
/// 对每个元素执行指定操作,并返回最新的IEnumerable<T>(可读写)
/// </summary>
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Func<T, T> func)
{
var tempList = source.ToList();
for (int i = 0; i < tempList.Count; i++)
tempList[i] = func(tempList[i]);
return tempList;
}
但是不建议这么做,迭代器应该是只读的。using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class P
{
public int id { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<P> list = new List<P>() { new P { id = 1 }, new P { id = 2 }, new P { id = 3 } };
list.ForEach(x => x.id = x.id + 1);
foreach (P p in list)
{
Console.WriteLine(p.id);
}
}
}
}
2
3
4
请按任意键继续. . .
如果P是Struct,就不能这么写,得用elect
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
struct P
{
public int id { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<P> list = new List<P>() { new P { id = 1 }, new P { id = 2 }, new P { id = 3 } };
list = list.Select(x => new P { id = x.id + 1 }).ToList();
foreach (P p in list)
{
Console.WriteLine(p.id);
}
}
}
}