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查询中使用.