根据列表B中的属性从列表A中设置属性

时间:2015-10-01 21:10:28

标签: c# wpf list

我有两个清单: List<UserModel>List<UserDetails>

其中:

public class UserModel
{
    public int RoleId { get; private set; }
    public IEnumerable<UserType> UserType
    {
        get { return Enum.GetValues(typeof(UserType)).Cast<UserType>(); }
    }

    private UserType selectedUserType;
    public UserType SelectedUserType
    {
        get { return selectedUserType; }
        set
        {
           .....
        }
    }
}

public class UserDetails
{
    public bool IsPrimary { get; set; }
    public int RoleId { get; set; }
    ...
}

如果bool IsPrimary设置为UserDetails,我需要将trueSelectedUserType设置为Primary,但仅针对同一RoleId ... UserTypeEnum : Primary, Secondary

那么,我该怎么做呢?有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您应该考虑使用LINQ表达式加入这两个列表。将join函数的结果(也应根据UserType过滤)转换为新列表并循环遍历所有元素并将布尔值设置为true。

查看following question

答案 1 :(得分:0)

您可以按其RoleID迭代它们,如下所示:

List<UserModel> models = ...;
List<UserDetails> details = ...;

models.Foreach(x => details
    .Where(y => y.RoleId == x.RoleId)
    .ToList()
    .Foreach(y => y.IsPrimary = (x.SelectedUserType == UserType.Primary))
);

它的作用是迭代UserModels,而不是foreach UserModel迭代所有UserDetails并过滤那些具有相同RoleId的人,而不是设置IsPrimary true仅当匹配SelectedUserType的{​​{1}}为UserModel时,才会{}} {} {}。{/ p>

这也可以在没有Linq的情况下完成,如下所示:

UserType.Primary

答案 2 :(得分:0)

我假设您有IEnumerable<UserModel>IEnumerable<UserDetails>。我已经改变了一些类来简化问题。

var userDetails = new List<UserDetails>{ 
    new UserDetails(){ Id = 1, RoleId = 1 },
    new UserDetails(){ Id = 2, RoleId = 1 },
    new UserDetails(){ Id = 3, RoleId = 2 },
    new UserDetails(){ Id = 4, RoleId = 2 }
};

var userModels = new List<UserModel> {
    new UserModel { RoleId = 1, SelectedUserType = UserType.Primary },
    new UserModel { RoleId = 2, SelectedUserType = UserType.Secondary },
    new UserModel { RoleId = 3, SelectedUserType = UserType.Primary }
};

然后,你需要将IsPrimary设置为UserDetails 1和2的true,对吗?

var userDetailsToSetPrimary = 
    (from userDetail in userDetails
    join userModel in userModels
    on userDetail.RoleId equals userModel.RoleId
    where userModel.SelectedUserType == UserType.Primary
    select userDetail);

foreach(userDetail in userDetailsToSetPrimary)
    userDetail.IsPrimary = true;