我想要更改LINQ查询结果对象的某些属性,而不需要创建一个新对象并手动设置每个属性。这可能吗?
例如:
例如:
var list = from something in someList
select x // but change one property
var list = from something in someList
select x // but change one property
var item = (from something in someList
select x).firstordefault();
可以获取item
,然后您可以执行item.prop1=5;
来更改特定属性。
或者,您是否希望从数据库中获取项目列表,并将返回的列表中每个项目的属性prop1
更改为指定值?
如果是这样,您可以这样做(我使用VB进行操作,因为我更熟悉):
dim list = from something in someList select x
for each item in list
item.prop1=5
next
(list
将包含所有带有您更改的项目)
list.Where(t => t.Id == 1).ToList().ForEach(t => t.Property = "something");
尝试过并且有效,引用自这里:
https://visualstudiomagazine.com/articles/2019/07/01/updating-linq.aspx
我遇到了与OP问题完全相同的要求,但我没有看到任何在上面使用表达式回答的地方。
假设x
是MyType
类型,你可以调用一个返回MyType
并接受x
的方法。在该方法内部,您可以进行所有想要的修改。代码将如下所示。
var list = from something in someList
select GetModifiedObject(x); // but change one property
private MyType GetModifiedObject(MyType x)
{
x.Property1 = "Changed Value";
return x;
}
User u = UserCollection.Single(u => u.Id == 1);
u.FirstName = "Bob"