没问题
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,就不能这么写,得用electusing 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);
}
}
}
}
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,就不能这么写,得用electusing 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);
}
}
}
}
dt.AddDays(1)为啥还是今天?
ForEach(var p in listxx)
{
Add(p);
}private void Add(P p)
{
p.x=p.x+6;
}
/// <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;
}
但是不建议这么做,迭代器应该是只读的。
listxx.Select(s =>
{
s.ID = s.ID + 6;
return 0;
}).ToArray();
我倒觉得微软不加只是偶尔发懒而已,没有应该只读一说,因为后来 ParallelEnumerable 就内置了 ForAll = =
listxx.AsParallel().ForAll(p=>p.x=p.x+6);但是,上边一切都有个前提,
如果你的listxx的元素类型是值类型,以上方法统统不管用,老老实实循环赋值吧= =