Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat LINQ Query

Tags:

c#

linq

Given my current extension method:

public static List<char> rotate(this List<char> currentList, int periodes) {
    if (periodes != 1) {
        int x = currentList.Count() - 1;
        return rotate(currentList.Skip(x).
             Concat(currentList.Take(x)).ToList<char>(), periodes - 1);
    }
    return currentList;
}

Original State:

ring = new List<char>() { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };

Current Result for ring.rotate(10);

J A B C D E F G H I
I J A B C D E F G H
H I J A B C D E F G
G H I J A B C D E F
F G H I J A B C D E      Recursive Steps
E F G H I J A B C D
D E F G H I J A B C
C D E F G H I J A B
B C D E F G H I J A

A B C D E F G H I J      Result

Is there any way to get rid of this while loop and any chance to integrate the repetition into the LINQ query?

Best
Henrik

like image 936
Henrik P. Hessel Avatar asked Sep 30 '10 15:09

Henrik P. Hessel


1 Answers

Skip i and concat i

public static class Ex
{
    public static List<char> Rotate(this List<char> c, int i)
    {
        i %= c.Count;
        return c.Skip(i).Concat(c.Take(i)).ToList();
    }
}

class Program
{
    static void Main()
    {
        List<char> chars = new List<char>();

        for (int i = 65; i < 75; ++i)
        {
            chars.Add((char)i);
        }

        var r1 = chars.Rotate(10); // A B C D E F G H I J
        var r2 = chars.Rotate(1); // B C D E F G H I J A
        var r3 = chars.Rotate(101); // B C D E F G H I J A
        var r4 = chars.Rotate(102); // C D E F G H I J A B

        Console.ReadLine();
    }
}
like image 68
BrunoLM Avatar answered Oct 11 '22 13:10

BrunoLM