assign value using linq

后端 未结 4 1662
孤城傲影
孤城傲影 2020-12-07 18:51
public class Company
{
    public int id { get; set; }
    public int Name { get; set; }
}

List listofCompany = new List();

相关标签:
4条回答
  • 2020-12-07 19:17

    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";
    

    UPDATE

    For multiple items (condition is met by multiple items):

     listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");
    
    0 讨论(0)
  • 2020-12-07 19:22

    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);
    
    0 讨论(0)
  • 2020-12-07 19:34

    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"
                    }
    
    0 讨论(0)
  • 2020-12-07 19:36

    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;}
    
    0 讨论(0)
提交回复
热议问题