1

I have this code and want to do the same with a linq statement.

foreach (var field in fieldExtension)
     {
          if (field.Name.Equals(item.Name))
          {
                field.Access = true;
          }
     }

It is easy to iterate over the list with:

fieldExtension.Where(field => field.Name.Equals(item.Name));

But is it posible to assign a value to the variable we have found in the list? I thought about something like this:

fieldExtension.Where(field => field.Name.Equals(item.Name)).Select(field => field.Access = true);

Does anybody know a way to do it correctly with linq? Because I don't want to split it up. Which would also work.

var result = fieldExtension.Where(field => field.Name.Equals(item.Name)).ToList();
result.FirstOrDefault().Access = true;
Florin M
  • 445
  • 1
  • 5
  • 18

1 Answers1

3

Why do you insist on linq? its not a good practice to use linq alll the time.

How ever you can mix linq with foreach.

foreach (var field in fieldExtension.Where(f => f.Name.Equals(item.Name)))
{
    field.Access = true;
}
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • In my company they prevere linq because of the readability and i wanted to know where the limits of linq are. but I think I will go with this mix. – Florin M Feb 19 '16 at 09:44