Reputation: 321
I want to use linq to change one of the property in my list, but this didn't work, do not create a new variable(this is a simple example, actual List have many properties)
List<string> aaa = new List<string>()
{
"a", "b"
};
aaa.Where(o => o == "b").Select(o => {
o = "c";
return o;
} ).ToList();
Upvotes: 0
Views: 79
Reputation: 156988
LINQ is a query language, you can 'ask' things, but it is hard to modify something using LINQ. And you shouldn't do that.
Changing an objects state in an enumerator is usually a bad thing, so consider to use a foreach
loop.
If you want to change the output, rather than the actual elements, you can do this:
var list = aaa.Select(o => o == "b" ? "c" : o).ToList();
Upvotes: 6
Reputation: 194
Try:
List<string> aaa = new List<string>()
{
"a", "b"
};
aaa = aaa.Select(o => {
return o == "b" ? "c" : o
}).ToList();
Upvotes: 0