我有一个嵌套 foreach语句,它成功地完成了我想做的事情。唯一的问题是,它看起来很乱。如何重构代码以使其更具可读性和简洁性?List<int> dofm = new List<int>();var dayOfMonth = Convert.ToString(ut.dayOfMonth);dofm = dayOfMonth .Split(',') .Select(s => { int.TryParse(s, out int i); return i - 1; }) .ToList();foreach (var a in model.Schedule.DofMInfo){ foreach (var b in dofm) { if (a.DofMID.Equals(b)) { a.IsChecked = true; } }}
2 回答
哔哔one
TA贡献1854条经验 获得超8个赞
您可以使用Join:
var items = model.Schedule.DofMInfo
.Join(dofm, dmi => dmi.DofMID, d => d, (dmi, d) => dmi);
foreach (var item in items)
{
item.IsChecked = true;
}
慕哥9229398
TA贡献1877条经验 获得超6个赞
我建议这样的事情:
// HashSet is faster than List<T> on Contains: O(1) vs. O(N)
HashSet<int> dofm = new HashSet<int>(dayOfMonth
.Split(',')
.Select(s => int.TryParse(s, out int i) ? i - 1 : -1));
// Second loop can be changed into "Contains"
foreach(var a in model.Schedule.DofMInfo)
if (dofm.Contains(a.DofMID))
a.IsChecked = true;
- 2 回答
- 0 关注
- 237 浏览
添加回答
举报
0/150
提交
取消