用linq更新Complex对象列表的元素

时间:2012-12-27 15:31:33

标签: linq c#-4.0 linq-to-entities linq-to-objects

大家好,并提前感谢解决方案

我有这些对象

    List<AccessModuleInfo> listOfAccessModuleInfo = new List<AccessModuleInfo>();

    public class AccessModuleInfo
    {
       public int AccessModuleId { get; set; }
       public string AccessModuleName { get; set; }
       public List<AccessRoleInfo> ListOfAccessRole { get; set; }

     }

    public class AccessRoleInfo
    {
      public int AccessRoleId { get; set; }
      public string AccessRoleName { get; set; }
      public bool AccessRoleValue { get; set; }
    }

我收到已填充的listOfAccessModuleInfo,当我尝试更新特定AccessModuleInfo中的AccessRoleValue时,所有具有相同AccessRoleId的AccessRoleValue都会更新。

我只想更新特定AccessModuleInfo的AccessRoleValue(例如,使用AccessModuleId = 4)

由于

1 个答案:

答案 0 :(得分:0)

通常这样的事情应该可以正常工作:

// You didn't confuse == vs = did you?
// Single also helps us debug and ensure we're only getting one result
var itemToUpdate = listOfAccessModuleInfo.Where(x => x.AccessModuleId == 4).Single();
itemToUpdate.ListOfAccessRole.ForEach(x => x.AccessRoleValue = newValue);