如果第一个字典项执行此操作,则执行此操作

时间:2015-01-23 00:30:40

标签: c# linq c#-4.0

我将一个SortedDictionary数组传递给一个函数,我需要循环遍历字典中的项目。如果它是第一个项目,请执行X,否则对于字典中的所有其他项目,执行Y.

SortedDictionary<string,int> eventsArray

找到了这个,但它不起作用:

foreach (var eventItem in eventsArray)
{
    if (eventsArray.Keys.First())
        item.firstStuff();

    else if (items.Last() == item)
        item.lastStuff();

    item.otherStuff();
}

3 个答案:

答案 0 :(得分:3)

你说:

  

如果是第一个项目,请执行X,否则对于字典中的所有其他项目,执行Y.

在这种情况下,您无需检查最后一项。试试这个:它简单,易读且快速:

bool isFirstItem = true; // when we enter the loop we know we deal with the first item
foreach (var eventItem in eventsArray)
{
    if (isFirstItem)
    {
        item.firstStuff();
        isFirstItem = false; // next item we deal with is not the first item
    }
    else
        item.otherStuff();
}

答案 1 :(得分:1)

Quality Catalyst尝试根据您的描述提供解决方案。既然不清楚你是否想要在你的描述中描述的行为,或者你所分享的例子中,这里是对你在这个例子中想要完成的事情的抨击:

var firstItem = eventsArray.First();
var lastItem = eventsArray.Last();
foreach (var eventItem in eventsArray)
{
    if (eventItem.Key == firstItem.Key)
        item.firstStuff();
    else if (eventItem.Key == lastItem.Key)
        item.lastStuff();
    else
        item.otherStuff();
}

然而,在这个例子中很难辨别item是什么,但是因为你的eventItem是一个字符串,我认为它接近你想要的。

答案 2 :(得分:0)

您可以这样做:

SortedDictionary<string,int> dict = new SortedDictionary<string,int>();
IEnumerator<KeyValuePair<string,int>> dictWalker = dict.GetEnumerator();
if ( !dictWalker.MoveNext() )
{
  ProcessFirstItem( dictWalker.Current ) ;
  while ( !dictWalker.MoveNext() )
  {
    ProcessOtherItems(dictWalker.Current) ;
  }
}

或者你可以使它成为通用的LINQ扩展,如下所示:

public static class Extensions
{

  public static IEnumerable<T> Apply<T>( this IEnumerable<T> sequence , Action<T> firstAction , Action<T> middleAction , Action<T> lastAction )
  {
    IEnumerator<T> visitor = sequence.GetEnumerator();
    bool           hasCurr = visitor.MoveNext() ;
    T              curr    = hasCurr ? visitor.Current : default(T) ;
    bool           hasNext = visitor.MoveNext() ;
    T              next    = hasNext ? visitor.Current : default(T) ;
    Action<T>      noop    = x => {} ;
    Action         advance = () => {
      hasCurr = hasNext ;
      curr    = next    ;
      hasNext = visitor.MoveNext();
      next    = hasNext ? visitor.Current : default(T) ;
    } ;

    firstAction  = firstAction  ?? noop ;
    middleAction = middleAction ?? noop ;
    lastAction   = lastAction   ?? noop ;

    if ( hasCurr )
    {
      firstAction(curr);
      yield return curr;
      advance();
    }

    while ( hasCurr && hasNext )
    {
      middleAction(curr) ;
      yield return curr;
      advance();
    }

    if ( hasCurr )
    {
      lastAction(curr);
      yield return curr;
      advance();
    }

    if ( hasCurr || hasNext ) { throw new InvalidOperationException("Well, this is embarassing now, isn't it?"); }

  }
}

干杯!

相关问题