我想改变一个LINQ查询结果对象的一些属性,而不需要创建一个新的对象和手动设置每个属性。这可能吗?

例子:

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;更改特定的属性。

或者您想从db中获得一个项目列表,并让它将返回列表中每个项目的属性prop1更改为指定的值? 如果是这样的话,你可以这样做(我在VB中这样做,因为我更了解它):

dim list = from something in someList select x
for each item in list
    item.prop1=5
next

(列表将包含您的更改返回的所有项)

其他回答

我不确定查询语法是什么。下面是扩展的LINQ表达式示例。

var query = someList.Select(x => { x.SomeProp = "foo"; return x; })

它所做的是使用匿名方法vs和表达式。这允许您在一个lambda中使用多个语句。因此,您可以将设置属性和返回对象这两个操作结合到这个稍微简洁的方法中。

如果你想用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();

总是返回项目,即使你不做任何改变。这样它将被保存在列表中。

我遇到了确切的要求(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;
}
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

(列表将包含您的更改返回的所有项)

如果你只是想更新所有元素的属性,那么

someList.All(x => { x.SomeProp = "foo"; return true; })