从排序列表C#中的下一个和上一个元素中检索值

时间:2013-03-11 09:16:57

标签: c#

我有一个排序列表,它将传递两个元素并比较两个元素。 C#中的SortedList类中是否有一个函数可以执行下一个和之前的操作?我得到了一些.Skip的帮助,但由于密钥是可变的,它会如何工作?我需要做的就是接受第一个元素和第二个元素,然后跳到第三个和第四个,第五个和第六个,等等。我希望它像LinkedList的“.next.next”一样简单。

  double velocity = positionList.Values.Skip(1);

编辑:positionList是类型

   <double, HandCoordinate>
   HandCoordinate = {double, double, double}

这有帮助吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

  List<int> ints = new List<int>();
  ints.Add(1);
  ints.Add(2);
  ints.Add(3);
  ints.Add(4);
  for (int i = 0; i < ints.Count; i += 2)
  {
    var pair = ints.Skip(i).Take(2);
    var first = pair.First();
    var last = pair.Last();
  }

注意:这应该有效,与理论类型无关。除非类型是完全不同的格式。

没有Skip()

var pair = new { First = ints[i], Second = ints[i += 1] };

答案 1 :(得分:0)

这个问题有点不清楚。我假设您需要从列表中获取一对东西?

编写一个扩展方法相当容易,该方法将显示来自IEnumerable的一系列项目:

using System;
using System.Collections.Generic;

namespace Demo
{
    internal static class Program
    {
        public static void Main()
        {
            double[] test = new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

            foreach (var pair in test.AsPairs()) // This is how you use it.
            {
                Console.WriteLine("({0}, {1})", pair.Item1, pair.Item2);
                // Or simply: Console.WriteLine(pair);
            }
        }
    }

    public static class EnumerableExt
    {
        public static IEnumerable<Tuple<T, T>> AsPairs<T>(this IEnumerable<T> sequence)
        {
            bool isFirst = true;
            T first = default(T);

            foreach (var item in sequence)
            {
                if (isFirst)
                {
                    first = item;
                    isFirst = false;
                }
                else
                {
                    isFirst = true;
                    yield return new Tuple<T, T>(first, item);
                }
            }
        }
    }
}

答案 2 :(得分:0)

SortedList类继承IEnumerator,因此您可以使用它:

SortedList list = ...
var listEnumerator = ((IEnumerable)list).GetEnumerator();
Pair<MyType> pair = null
do
{
    pair = Pair.Next<MyType>(listEnumerator);
    ...
}
while(pair != null)

...

class Pair<T>
{
    public T First {get; set;}
    public T Second {get; set;}

    public static Pair<T> Next<T>(IEnumerator enumerator)
    {
        var first = enumerator.Current;
        if(enumerator.MoveNext())
        {
           return new Pair<T>
               {
                   First = (T)first,
                   Second = (T)enumerator.Current,
               }
        }
        return null;
    }
}