重构嵌套的foreach语句

时间:2018-07-24 14:15:59

标签: c#

我有一个嵌套 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 个答案:

答案 0 :(得分:3)

您可以使用Join

var items = model.Schedule.DofMInfo
    .Join(dofm, dmi => dmi.DofMID, d => d, (dmi, d) => dmi);

foreach (var item in items)
{
    item.IsChecked = true;
}

答案 1 :(得分:2)

我建议这样:

// 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;