我有两个清单:
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
,我需要将true
从SelectedUserType
设置为Primary
,但仅针对同一RoleId
... UserType
是Enum : Primary, Secondary
。
那么,我该怎么做呢?有什么想法吗?
答案 0 :(得分:0)
您应该考虑使用LINQ表达式加入这两个列表。将join函数的结果(也应根据UserType过滤)转换为新列表并循环遍历所有元素并将布尔值设置为true。
答案 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;