public class Company
{
public int id { get; set; }
public int Name { get; set; }
}
List<Company> listofCompany = new List<Company>();
这是我的公司列表集合,我想使用LINQ
为Name属性赋值listofCompany.Where(d => d.Id = 1);
(我想要公司ID 1的名称属性)
如何分配。?
答案 0 :(得分:97)
使用 Linq 将是:
listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";
<强>更新强>
这可以简化为......
listOfCompany.FirstOrDefault(c =&gt; c.id == 1).Name =“Whatever Name”;
对于多个项目(条件由多个项目满足):
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");
答案 1 :(得分:5)
您可以创建扩展方法:
public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
foreach(var item in self) {
action(item);
yield return item;
}
}
然后在代码中使用它:
listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);
答案 2 :(得分:2)
也可以这样做
foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
{
//do your stuff here
company.Id= 2;
company.Name= "Sample"
}
答案 3 :(得分:1)
请注意,它只会更新公司ID为1的第一家公司。对于多个
(from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";
对于多次更新
from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name"; return c;}