我想改变一个LINQ查询结果对象的一些属性,而不需要创建一个新的对象和手动设置每个属性。这可能吗?
例子:
var list = from something in someList
select x // but change one property
我想改变一个LINQ查询结果对象的一些属性,而不需要创建一个新的对象和手动设置每个属性。这可能吗?
例子:
var list = from something in someList
select x // but change one property
当前回答
我更喜欢这个。它可以与其他linq命令组合使用。
from item in list
let xyz = item.PropertyToChange = calcValue()
select item
其他回答
这对于标准查询操作符是不可能的——它是语言集成查询,而不是语言集成更新。但是您可以将更新隐藏在扩展方法中。
public static class UpdateExtension
{
public static IEnumerable<Car> ChangeColorTo(
this IEnumerable<Car> cars, Color color)
{
foreach (Car car in cars)
{
car.Color = color;
yield return car;
}
}
}
现在您可以像下面这样使用它。
cars.Where(car => car.Color == Color.Blue).ChangeColorTo(Color.Red);
如果你想用Where子句更新项,使用.Where(…)将截断你的结果:
list = list.Where(n => n.Id == ID).Select(n => { n.Property = ""; return n; }).ToList();
你可以像这样更新列表中的特定项目:
list = list.Select(n => { if (n.Id == ID) { n.Property = ""; } return n; }).ToList();
总是返回项目,即使你不做任何改变。这样它将被保存在列表中。
var item = (from something in someList
select x).firstordefault();
会得到item,然后item。prop1=5;更改特定的属性。
或者您想从db中获得一个项目列表,并让它将返回列表中每个项目的属性prop1更改为指定的值? 如果是这样的话,你可以这样做(我在VB中这样做,因为我更了解它):
dim list = from something in someList select x
for each item in list
item.prop1=5
next
(列表将包含您的更改返回的所有项)
User u = UserCollection.Single(u => u.Id == 1);
u.FirstName = "Bob"
在2020年,我使用MoreLinq管道方法。https://morelinq.github.io/2.3/ref/api/html/M_MoreLinq_MoreEnumerable_Pipe__1.htm