Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign value using linq

Tags:

c#

linq

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.?

like image 612
PramodChoudhari Avatar asked Mar 21 '11 10:03

PramodChoudhari


4 Answers

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");
like image 152
Aliostad Avatar answered Oct 22 '22 11:10

Aliostad


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);
like image 21
TcKs Avatar answered Oct 22 '22 10:10

TcKs


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"
                }
like image 3
mini998 Avatar answered Oct 22 '22 12:10

mini998


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;}
like image 1
Sanjeevakumar Hiremath Avatar answered Oct 22 '22 12:10

Sanjeevakumar Hiremath