一种简洁的编写循环的方法,可针对集合中的第一个项目进行特殊逻辑处理。

13

经常情况下我需要编写循环,为第一个项目提供特殊情况的处理,但代码似乎从来都不像理想情况下那么清晰。

除了重新设计C#语言之外,编写这些循环的最佳方式是什么?

// this is more code to read then I would like for such a common concept
// and it is to easy to forget to update "firstItem"
foreach (x in yyy)
{
  if (firstItem)
  {
     firstItem = false;
     // other code when first item
  }
  // normal processing code
}

// this code is even harder to understand
if (yyy.Length > 0)
{
   //Process first item;
   for (int i = 1; i < yyy.Length; i++)
   {  
      // process the other items.
   }
}

3
我认为检查布尔值(你的第一个例子)没有任何问题,任何人看到它都能迅速知道你正在做什么。 - JD Isaacks
12个回答

0

我想到的另一个选项是:

enum ItemType
{
  First,
  Last,
  Normal
}

list.Foreach(T item, ItemType itemType) =>
{
   if (itemType == ItemType.First)
   {
   }

   // rest of code
};

编写扩展方法留给读者作为练习...此外,应该使用两个布尔标志“IsFirst”和“IsLast”,而不是ItemType枚举,或者ItemType是一个具有“IsFirst”和“IsLast”属性的对象吗?


0

我的解决方案:

foreach (var x in yyy.Select((o, i) => new { Object = o, Index = i } )
{
  if (x.Index == 0)
  {
    // First item logic
  }
  else
  {
    // Rest of items
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接