Retry LINQ Query

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; } 

The initial state:

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

Current result for ring.rotate(10);

 JABCDEFGHI IJABCDEFGH HIJABCDEFG GHIJABCDEF FGHIJABCDE Recursive Steps EFGHIJABCD DEFGHIJABC CDEFGHIJAB BCDEFGHIJA 

 ABCDEFGHIJ Result 

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

Best
Henric

+6
c # linq
source share
3 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); // ABCDEFGHIJ var r2 = chars.Rotate(1); // BCDEFGHIJA var r3 = chars.Rotate(101); // BCDEFGHIJA var r4 = chars.Rotate(102); // CDEFGHIJAB Console.ReadLine(); } } 
+3
source share

This should lead to the same thing as the original solution, and compensate for the -1 problem:

 public static List<char> rotate2(this List<char> currentList, int periodes) { int start = (currentList.Count - periodes) + 1; return currentList.Skip(start).Concat(currentList.Take(start)).ToList(); } 

Edit

I put this in a console application, the results look the same for me

 class Program { static void Main(string[] args) { List<char> s = "ABCDEFGHIJ".ToList(); for (int x = 0; x < 10; x++) { s.rotate(x+ 1).ForEach(Console.Write); Console.WriteLine(); } Console.WriteLine(); for (int x = 0; x < 10; x++) { s.rotate2(x + 1).ForEach(Console.Write); Console.WriteLine(); } Console.ReadLine(); } } static class so { public static List<char> rotate(this List<char> currentList, int periodes) { while (periodes != 1) { int x = currentList.Count() - 1; return rotate(currentList.Skip(x). Concat(currentList.Take(x)).ToList<char>(), periodes - 1); } return currentList; } public static List<char> rotate2(this List<char> currentList, int periodes) { int start = (currentList.Count - periodes) + 1; return currentList.Skip(start).Concat(currentList.Take(start)).ToList(); } } 
+3
source share

To completely write the Linq console program, how about:

 class Program { static void Main(string[] args) { var ring = Enumerable.Range(97, 10).Select(x => (char)x).ToList(); Console.WriteLine(string.Join("\n", Enumerable.Range(1, 10).Select(x => new string(ring.rotate(x).ToArray())))); Console.ReadLine(); } } 
+1
source share

All Articles