0

Im facing a very strange problem. I have a list and am trying to update one of its inner structure field from the following for loop.

foreach (var item in AppUserDetail )
            {
                int AppUserID = item.AppUserId;
                List<int> list = templateCategory.AppUserTemplateCategorySecurityGroupXrefs.Where(a => a.AppUserId == AppUserID).Select(b => b.SecurityGroupId).ToList();

                item.AppUserSecurityGroupXrefs.Where(a => list.Contains(a.SecurityGroupId)).Select(b => b.SecurityGroup).Select(c =>  c.Selected = true);
                bool s = item.AppUserSecurityGroupXrefs.Where(a => list.Contains(a.SecurityGroupId)).Select(b => b.SecurityGroup).Select(c => c.Selected).FirstOrDefault();

             }
return AppUserDetail;

On the third line in loop, as you can see Im changing a value to True using select itself. When I run the application the value looks unchanged on the returning object. But if we execute the same line in immediate window by putting a break point inside the loop, it update the Data and it reflects at the returning object AppUserDetail. Am really getting confused why its only update from Immediate window, not from direct code execution.

item.AppUserSecurityGroupXrefs.Where(a => list.Contains(a.SecurityGroupId)).Select(b => b.SecurityGroup).Select(c => c.Selected = true);

Richard
  • 106,783
  • 21
  • 203
  • 265
Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132

1 Answers1

1
item.AppUserSecurityGroupXrefs.Where(a => list.Contains(a.SecurityGroupId)).Select(b => b.SecurityGroup).Select(c =>  c.Selected = true);

Select is lazy, since nothing enumerates the enumerable it returns nothing will be executed. The immediate window implicitly enumerates the result to display it, but that will not normally happen in the built code.

(And even if it were, the purpose of Select is to return a new object – a projection of the object passed in – not to modify something. Therefore weirdness is likely.)

I think you really want an Enumerable.ForEach extension which is designed to process the results of a LINQ expression. Your own implementation is very easy.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • Sir, can you please modify the above using Enumerable.foreach. Im not so fluent with Linq – Sandeep Thomas Jan 10 '18 at 17:44
  • @sforsandeep a search for `Enumerable.foreach` should give plenty of material. Personally I think it misses the underlying concept of LINQ, and to process all results one should simply use a `foreach` loop. – Richard Jan 10 '18 at 20:02