我想改变一个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表达式示例。
var query = someList.Select(x => { x.SomeProp = "foo"; return x; })
它所做的是使用匿名方法vs和表达式。这允许您在一个lambda中使用多个语句。因此,您可以将设置属性和返回对象这两个操作结合到这个稍微简洁的方法中。
其他回答
我更喜欢这个。它可以与其他linq命令组合使用。
from item in list
let xyz = item.PropertyToChange = calcValue()
select item
使用ForEach
var list = from something in someList;
list.ForEach(x => x.Property = value);
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
(列表将包含您的更改返回的所有项)
在2020年,我使用MoreLinq管道方法。https://morelinq.github.io/2.3/ref/api/html/M_MoreLinq_MoreEnumerable_Pipe__1.htm
由于我在这里没有找到我认为最好的解决方案的答案,下面是我的方法:
使用“选择”来修改数据是可能的,但只是有一个技巧。总之,"选择"不是为这个设计的。它只在与“ToList”一起使用时执行修改,因为Linq在需要数据之前不会执行。 无论如何,最好的解决方案是使用“foreach”。在下面的代码中,你可以看到:
class Person
{
public int Age;
}
class Program
{
private static void Main(string[] args)
{
var persons = new List<Person>(new[] {new Person {Age = 20}, new Person {Age = 22}});
PrintPersons(persons);
//this doesn't work:
persons.Select(p =>
{
p.Age++;
return p;
});
PrintPersons(persons);
//with "ToList" it works
persons.Select(p =>
{
p.Age++;
return p;
}).ToList();
PrintPersons(persons);
//This is the best solution
persons.ForEach(p =>
{
p.Age++;
});
PrintPersons(persons);
Console.ReadLine();
}
private static void PrintPersons(List<Person> persons)
{
Console.WriteLine("================");
foreach (var person in persons)
{
Console.WriteLine("Age: {0}", person.Age);
;
}
}
}
在"foreach"之前,你也可以做一个linq选择…