Reputation: 217
Please, refer to this other post: assign value using linq
With this expression we can update one value in multiple items of a list:
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");
Is it possible to update more than one value? Is this more efficient that implementing a foreach structure and set the multiple values in it?
Upvotes: 0
Views: 3405
Reputation: 45947
Approach without ForEach
and only one iteration instead of two
listOfCompany = listOfCompany.Select(x => {
x.Name = x.id == 1 ? "Whatever Name" : x.Name;
x.Name2 = x.id == 1 ? "Whatever Name" : x.Name2;
return x;
}).ToList();
Approach without Linq (probably the fastes one)
for (int i = 0; i < listOfCompany.Count; i++)
{
if (listOfCompany[i].id == 1)
{
listOfCompany[i].Name = "Whatever Name";
listOfCompany[i].Name2 = "Whatever Name";
}
}
Upvotes: 0
Reputation: 11635
LINQ is fun and all, but IMHO you should try to go for readable and maintainable code. When you need to update several fields I would argue that a regular foreach
would suit you better.
foreach(var item in listOfCompany.Where(c=> c.id == 1))
{
item.Name = "Whatever Name";
item.Property = 1;
//..
}
As for if it's more efficient, I don't think you would notice it. You can always study the reference source - it's basically only calling an Action
for each item.
Upvotes: 2
Reputation: 505
try code Just use { } and Every item End use ; semicolon
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => { cc.Name = "Whatever Name";cc.Contacts="Manager";});
Upvotes: 0
Reputation: 31239
You can do it like this:
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc =>
{
cc.Name = "Whatever Name";
cc.OtherField="Whatever field";
});
Upvotes: 2
Reputation: 27055
Just use brackets:
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc =>
{
cc.Name = "Whatever Name";
cc.Name = "Whatever Name";
cc.Name = "Whatever Name";
});
Or use a ref to a method:
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(UpdateCompany);
private void Function(Company cc)
{
cc.Name = "Whatever Name";
cc.Name = "Whatever Name";
cc.Name = "Whatever Name";
}
Upvotes: 3