简体   繁体   中英

How to go back to the start of a list?

I'm trying to use the methods Skip() and Take() to get values from a list. But I can't manage to go back to the start of the list when the list ends.

List<string> list = new List<string>();
list.Add("Duck1");
list.Add("Duck2");
list.Add("Duck3");
list.Add("Duck4");
list.Add("Duck5");

var list2 = list.Skip(4).Take(3);

foreach(var a in list2) {
  Console.WriteLine(a);
}

The result is:

  • Duck5

The result that I'm looking for is:

  • Duck5
  • Duck1
  • Duck2

You can write a method that will make an IEnumerable<T> circular and then use that.

public static IEnumerable<T> ToCircular<T>(this IEnumerable<T> source)
{
    while(true)
    {
        foreach(var x in source) yield return x;
    }
}

Then you can do the following

List<string> list = new List<string>();
list.Add("Duck1");
list.Add("Duck2");
list.Add("Duck3");
list.Add("Duck4");
list.Add("Duck5");

var list2 = list.ToCircular().Skip(4).Take(3);

foreach(var a in list2){
    Console.WriteLine(a);
}

But be careful as this results in an infinite loop and you'd want to limit it when using it with Take or TakeWhile or First .

If you know that you're only going to need to "loop back" once, and you can simply use Concat:

var list2 = list.Concat(list).Skip(4).Take(3);

Otherwise I suggest juharr's answer . Just be aware that you need to be really careful with infinite IEnumerables. Many LINQ operations that need to consume the whole collection (eg .ToList() , .Reverse() , .OrderBy() ) will freeze up your application and cause it to run out of memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM