猿问

重构嵌套的 foreach 语句

我有一个嵌套 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;

        }

    }

}


慕容708150
浏览 238回答 2
2回答

哔哔one

您可以使用Join:var items = model.Schedule.DofMInfo&nbsp; &nbsp; .Join(dofm, dmi => dmi.DofMID, d => d, (dmi, d) => dmi);foreach (var item in items){&nbsp; &nbsp; item.IsChecked = true;}

慕哥9229398

我建议这样的事情:// HashSet is faster than List<T> on Contains: O(1) vs. O(N)HashSet<int> dofm = new HashSet<int>(dayOfMonth&nbsp; .Split(',')&nbsp; .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)&nbsp; if (dofm.Contains(a.DofMID))&nbsp; &nbsp; a.IsChecked = true;
随时随地看视频慕课网APP
我要回答