how to set value in List with out using foreach loop

242 views Asked by At

I am having two lists and filter based on a group of values.

 var UserIdList = response.Users.Select(p => p.Id).ToList();

 var filteredRecords = 
(from o in om.Organizations join u in om.Users on o.Id equals u.OrganizationId where UserIdList.Contains(u.Id)    
                 select new { Enabled = o.Enabled, Id = u.Id }).ToList();

Now i want to set 'Exists' property in 'response.Users' to true if 'Id' exists in filteredRecords.

Please let me know how can I set value with out using foreach loop. I have tried with

 response.Users.Where(x => x.Exists = (filteredRecords .Any(z => z.Id == x.Id))).ToList();

but could not succeed as it is giving only filter results. I want full records which are matched and which are not

2

There are 2 answers

0
Izzy On

As a direct response to:

Please let me know how can I set value with out using foreach loop. I have tried with

 response.Users.Where(x => x.Exists = (filteredRecords .Any(z => z.Id == x.Id))).ToList(); but could not succeed as it is giving only

filter results. I want full records which are matched and which are not

What you've done there is selected a collection of response user items you wish to have Exists set to true.

Now you need to set that bool in this filtered collection, and then return the full response collection afterwards, instead of returning the filtered collection.

I think this is where you're getting confused.

0
reckface On

Linq doesn't really support update scenarios as it's for querying data.

For lists however there's a ForEach extension method:

UserList
  .ToList()
  .ForEach(item=> item.Exists = filteredRecords.Any(f=> f.Id == item.Id));

Is this clearer to read and easier to understand than a foreach loop...

Edit (after question updates)

// You can't use this... it won't even compile, 
// x.Exists = ... is an assignment not a condition
response.Users.Where(x => x.Exists = (filteredRecords .Any(z => z.Id == x.Id))).ToList();

What you want to do is to work with a subset of users and update the values.

response
  .Users
  .Where(x=> filteredRecords.Any(z => z.Id == x.Id))
  .ToList() // This materialises your IEnumerable/IQueryable to allow the ForEach extension method
  .ForEach(x => x.Exists = true);

you could of course use:

var usersToEnable = response.Users.Where(x=> filteredRecords.Any(z => z.Id == x.Id);
foreach(var user in usersToEnable)
  user.Enabled = true;