Reputation: 29789
Is it possible to set property on each element from List using LINQ.
for example:
var users = from u in context.Users where u.Name == "George" select u;
foreach (User us in users){
us.MyProp = false;
}
Is it possible to make it cleaner ?
Upvotes: 43
Views: 76489
Reputation: 894
Looks dirty but if asked (just via select), I'll do it this way
var users = from u in context.Users where u.Name == "George"
select new User()
{
prop1 = u.prop1,
prop2 = u.prop2,
prop3 = true // update like here
};
if you wish to use some other C# function, you can also use linq functions and work on IEnumerable type of lists.
var users = context.Users.Where(u => u.Name == "George").ToList()
.Select(p => new User()
{
prop1 = p.prop1,
prop2 = p.prop2,
prop3 = ComputeHash(p) // update like here
});
Code above becomes IEnumerable because of the .ToList()
prior to the .Select()
Upvotes: 1
Reputation: 7852
How about:
context.Users.Where(u => u.Name == "George").Select(u => u.MyProp = false);
Upvotes: 0
Reputation: 19618
Or you can convert it to ToList() and use ForEach method.
users.ToList().ForEach(u => u.MyProp = false);
to update more than one properties
users.ToList().ForEach(u =>
{
u.property1 = value1;
u.property2 = value2;
});
Or like this
(from u in context.Users where u.Name == "George" select u).ToList()
.ForEach(u => u.MyProp = false);
Upvotes: 97
Reputation: 158389
What is cleaner is quite subjective. Personally, I find this approach hard to beat for clarity and simplicity:
foreach (User us in users.Where(u => u.Name == "George"))
{
us.MyProp = false;
}
Upvotes: 3
Reputation: 9799
If you're interested in in-memory update, that is the database is not going to be updated then you could use
var users = (from u in context.Users where u.Name == "George" select u).ToList();
users.ForEach(u => u.MyProp = "Something");
Upvotes: 1
Reputation: 9469
You can create your own ForEach extension method:
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var element in source)
{
action(element);
}
return source;
}
Then your code can be simplified to:
context.Users.Where(x => x.Name == "George").ForEach(u => u.MyProp = false);
EDIT: You could also yield return each item after the call to action() (no pun intended) to leave the deferred execution untouched.
Upvotes: 4