简体   繁体   English

如何将 go 返回到列表的开头?

[英]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.我正在尝试使用方法Skip()Take()从列表中获取值。 But I can't manage to go back to the start of the list when the list ends.但是当列表结束时,我无法将 go 回到列表的开头。

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鸭子5

The result that I'm looking for is:我正在寻找的结果是:

  • Duck5鸭子5
  • Duck1鸭1
  • Duck2鸭2

You can write a method that will make an IEnumerable<T> circular and then use that.您可以编写一个方法,使IEnumerable<T>循环,然后使用它。

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 .但要小心,因为这会导致无限循环,并且在将其与TakeTakeWhileFirst一起使用时,您需要限制它。

If you know that you're only going to need to "loop back" once, and you can simply use Concat:如果你知道你只需要“回环”一次,你可以简单地使用 Concat:

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

Otherwise I suggest juharr's answer .否则我建议juharr's answer Just be aware that you need to be really careful with infinite IEnumerables.请注意,您需要非常小心使用无限的 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.许多需要消耗整个集合的 LINQ 操作(例如.ToList() 、 .Reverse( .Reverse().OrderBy() )将冻结您的应用程序并导致它用完 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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