C# Collection - Order by an element (Rotate)

后端 未结 6 486
迷失自我
迷失自我 2021-01-23 17:05

I have an IEnumerable collection. Lets say it contains 5 points (in reality it is more like 2000)

I want to order this collection so that a spe

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 17:47

    Version without enumerating list two times, but higher memory consumption because of the T[]:

    public static IEnumerable Rotate(IEnumerable source, int count)
    {
        int i = 0;
    
        T[] temp = new T[count];
    
        foreach (var item in source)
        {
            if (i < count)
            {
                temp[i] = item;
            }
            else
            {
                yield return item;
            }
    
            i++;
        }
    
        foreach (var item in temp)
        {
            yield return item;
        }
    }
    
    [Test]
    public void TestRotate()
    {
        var list = new[] { 1, 2, 3, 4, 5 };
    
        var rotated = Rotate(list, 3);
    
        Assert.That(rotated, Is.EqualTo(new[] { 4, 5, 1, 2, 3 }));
    }
    

    Note: Add argument checks.

提交回复
热议问题