用Linq拼接IEnumerable

Cod*_*gue 7 c# linq linq-to-objects

是否有内置的方法来拼接IEnumerableLinq-To-Objects?

就像是:

List<string> options = new List<string>(); // Array of 20 strings
List<string> lastOptions = options.Splice(1, 5); // Gets me all strings 1 through 5 into a new list
Run Code Online (Sandbox Code Playgroud)

Jer*_*gen 18

尝试:

List<string> options = new List<string>();
List<string> lastOptions = options.Skip(0).Take(5).ToList();
Run Code Online (Sandbox Code Playgroud)

skip用于显示如何跳过x元素 (tnx drch)


你可以创建这样的东西:( 扩展方法)

public static class SpliceExtension
{
    public static List<T> Splice<T>(this List<T> list, int offset, int count)
    {
        return list.Skip(offset).Take(count).ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

但这只适用于列表.


你也可以使用它 IEnumerable<>

public static class SpliceExtension
{
    public static IEnumerable<T> Splice<T>(this IEnumerable<T> list, int offset, int count)
    {
        return list.Skip(offset).Take(count);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样List就不会完全迭代.

使用它像:

List<string> lastOptions = options.Splice(1, 5).ToList();
Run Code Online (Sandbox Code Playgroud)

我更喜欢这种方式,因为它可以在几个linq查询中使用.

  • 如果你不能/不能使用Linq,还有[List <T> .GetRange](http://msdn.microsoft.com/en-us/library/21k0e39c.aspx). (5认同)
  • 仅供参考,skip是要跳过的元素数,而不是要跳过的项的索引. (4认同)