Update In Linq
2012-03-16 17:22 barbarossia 阅读(219) 评论(0) 收藏 举报
http://stackoverflow.com/questions/3658028/linq-to-objects-update
And I write a code example to test perfomence.
class Program
{
static void Main(string[] args)
{
List<Person> source = Generate(10000, (c) =>
{
return c * 10;
});
List<Person> target = Generate(10000, (c) =>
{
return c * 20;
});
CodeTimer.Initialize();
CodeTimer.Time("UseLinq", 1, () => { UseLinq(source, target); });
CodeTimer.Time("UseList", 1, () => { UseList(source, target); });
//foreach (var s in source)
//{
// Console.WriteLine(string.Format("Person's Id is {0}, Age is {1}", s.Id, s.Age));
//}
Console.ReadLine();
}
static void UseLinq(List<Person> source, List<Person> target)
{
Func<Person, Person, Person> updateFunc = (s, t) => { s.Age = t.Age; return s; };
var update = (from s in source
join t in target on s.Id equals t.Id
select updateFunc(s, t)).ToList();
}
static void UseList(List<Person> source, List<Person> target)
{
foreach (Person s in source)
{
Person p = target.SingleOrDefault(t => t.Id == s.Id);
if (p != null)
{
s.Age = p.Age;
}
}
}
static List<Person> Generate(int num, Func<int, int> age)
{
List<Person> list = new List<Person>();
for (int i = 0; i <= num; i++)
{
Person p = new Person();
p.Id = i;
p.Age = age(i);
list.Add(p);
}
return list;
}
The result is:
浙公网安备 33010602011771号