title: Updating nested list values with Linq?
body: <p>I am trying to update a nested list in C# which looks like this</p>
  
  <p>List<code>&lt;Users</code>><br>
  - UserType<br>
  - List<code>&lt;UserComponents</code>><br>
  - - UserComponentKey<br>
  - - Count</p>
  
  <p>Here's a written example:<br>
  List of users:
  UserType = 1<br>
  UserComponents<br>
  - UserComponentKey = XYZ<br>
  - Count = 3  </p>
  
  <p>UserType = 2<br>
  UserComponents<br>
  - UserComponentKey = XYZ<br>
  - Count = 7</p>
  
  <p>I need to update UserComponentKey XYZ for UserType 2 only, currently my updates are broken and updates XYZ for all user types. Here is my current methods which do not work as they update the UserComponent count value for ALL usertypes which contain the specified component key, and not the specific usertype I am targeting.</p>
  
  <p>CLASSES:</p>
  
  <pre><code>public class Users
  {
      public string UserType { get; set; }
      public List&lt;UserComponent&gt; UserComponents { get; set; }
  }
  
  public class UserComponent
  {
      public string UserComponentKey { get; set; }
      public int Count { get; set; }
  }
  </code></pre>
  
  <p>METHOD 1: </p>
  
  <pre><code>Users.Where(us =&gt; us.UserType == "2")
       .First().UserComponents
       .Where(uc =&gt; uc.UserComponentKey == "XYZ")
       .First().Count = value;
  </code></pre>
  
  <p>METHOD 2:  </p>
  
  <pre><code>if(users.UserType == "2")
  {
     foreach(var component in users.UserComponents)
     {
         switch(component.UserComponentKey)
         {
            case "XYZ":
            component.Count = value;
            break;
         }
      }
  }
  </code></pre>
  
  <p>CODE GENERATING LIST (similar to):
      List UserComponents = new List();</p>
  
  <pre><code>if (Item.UserAddOn != null)
      {
          for (var i = 0; i &lt; Item.UserAddOn.First().Count; i++)
          {
              UserComponents.Add(new UserComponent
              {
                  UserComponentKey = Item.UserAddOn[i].ComponentKey,
                  Count = 0
               });
           }
      }
  
  if (Item.User != null)
      {
          for (var i = 0; i &lt; Item.User.First().Count; i++)
          {
               Users.Add(new User()
               {
                   UserType = Item.User[i].ComponentKey,
                   Count = 0,
                   UsersComponents = UserComponents
               });
           }
       }
  </code></pre>
  
  <p>I have stripped out actual values etc, but hopefully someone can point me in the right direction here. </p>
  
  <p>Thanks!</p>