我想知道是否有一种标准的方法可以从另一个列表的元素中创建一个列表,直到指定的索引,例如:
List1(1,2,3,4,5,6,7,8,9,0);
List2 = new List(List1, upToIndex = 4)
List2(1,2,3,4,5)
我需要一种非常快速的方法,如果有办法的话,我想避免简单的"for“循环。
发布于 2019-05-12 23:35:22
那list.GetRange(startIndex, count)
呢?
List<int> inputList = new List<int>() { 1,2,3,4,5,6,7,8,9,9};
List<int> newList = inputList.GetRange(0, 4); //Output: 1,2,3,4
如果您想使用startingIndex
和endingIndex
从给定列表中获得子列表,那么您可以做一些基本的数学运算
就像这样
List<int> newList = inputList.GetRange(startIndex, (endIndex - startIndex)); //(endIndex - startIndex) this will return count of sub list
或者您可以尝试@Crowcoder建议的Linq操作,
List<int> newList = inputList.Skip(startIndex).Take(endIndex).ToList();
如果您使用是C# 8,那么您可以使用range而不是Skip
和Take
,
var newList = inputList.Range[startIndex..count]; //where count will be (endIndex - startIndex)
发布于 2019-05-12 23:33:32
可以,您可以使用System.Linq
。
var subset = yourList.Take(4).ToList();
https://stackoverflow.com/questions/56100740
复制相似问题