简单的方法来更新使用LINQ IEnumerable的对象 [英] Simple way to update IEnumerable objects using LINQ
问题描述
假设我有一个业务对象就是这样,
Assume I have a business object like this,
class Employee
{
public string name;
public int id;
public string desgination;
public int grade;
}
List<Employee> lstEmp = new List<Employee>()
{
new Employee() { name="A",desgination="SE",id=1},
new Employee() { name="b",desgination="TL",id=2},
new Employee() { name="c",desgination="PL",id=3},
new Employee() { name="d",desgination="SE",id=4},
new Employee() { name="e",desgination="SSE",id=5},
};
如果我想更新员工年级到3的名称是SE,那我也写这样的事情
And if I want to update the employee grade to 3 whose designation is "SE", then I have to write something like this
lstEmp=lstEmp.Select(x =>
{
x.grade = (x.desgination == "SE") ? 3 : x.grade;
return x;
}).ToList();
但在这里使用时选择它会产生新的员工对象每次,而不是更新现有lstEmp,所以我有reassgin更新列表lstEmp。
But here when using select it will generate new employee object everytime, not updating the existing lstEmp, so I have to reassgin the updated list to lstEmp.
在我看来,频繁更新大量更新时,它会影响性能。对此有一个解决办法?
It seems to me it affects the performance when updating large updates frequently. Is there a workaround for this?
推荐答案
我相信默认LINQ方法doenst支持在线更新。但你可以创建自己的扩展方法才达到这个
I believe default LINQ methods doenst support inline updates. but you can create your own extension methods to achive this
public static void Update<TSource>(this IEnumerable<TSource> outer, Action<TSource> updator)
{
foreach (var item in outer)
{
updator(item);
}
}
和使用像这样
lstEmp.Update(x => x.grade = (x.desgination == "SE") ? 3 : x.grade);
这篇关于简单的方法来更新使用LINQ IEnumerable的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!