Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify only one or two field(s) in LINQ projections?

I have this LINQ query:

List<Customers> customers = customerManager.GetCustomers();

return customers.Select(i => new Customer {
    FullName = i.FullName,
    Birthday = i.Birthday, 
    Score = i.Score,
    // Here, I've got more fields to fill
    IsVip = DetermineVip(i.Score)
}).ToList();

In other words, I only want one or two fields of the list of the customers to be modified based on a condition, in my business method. I've got two ways to do this,

  1. Using for...each loop, to loop over customers and modify that field (imperative approach)
  2. Using LINQ projection (declarative approach)

Is there any technique to be used in LINQ query, to only modify one property in projection? For example, something like:

return customers.Select(i => new Customer {
    result = i // telling LINQ to fill other properties as it is
    IsVip = DetermineVip(i.Score) // then modifying this one property
}).ToList();
like image 767
Mehdi Emrani Avatar asked Mar 13 '13 06:03

Mehdi Emrani


1 Answers

you can use

return customers.Select(i => {
    i.IsVip = DetermineVip(i.Score);
    return i;
}).ToList();
like image 167
Omid Shariati Avatar answered Sep 29 '22 19:09

Omid Shariati