public class Company
{
public int id { get; set; }
public int Name { get; set; }
}
List<Company> listofCompany = new List<Company>();
this is my collection of company list I want to assign values to Name property using LINQ
listofCompany.Where(d => d.Id = 1);
(I want to assing name property of company id 1)
how do I assign it.?
using Linq would be:
listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";
UPDATE
This can be simplified to be...
listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";
For multiple items (condition is met by multiple items):
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");
You can create a extension method:
public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
foreach(var item in self) {
action(item);
yield return item;
}
}
And then use it in code:
listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);
It can be done this way as well
foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
{
//do your stuff here
company.Id= 2;
company.Name= "Sample"
}
Be aware that it only updates the first company it found with company id 1. For multiple
(from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";
For Multiple updates
from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name"; return c;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With