C# 如何从列表中获取特定范围(3 - 7)中的项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13141685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get items in a specific range (3 - 7) from list?
提问by Niels
What would be the most efficient way to select all the items in a specific range from a list and put it in a new one?
从列表中选择特定范围内的所有项目并将其放入新项目的最有效方法是什么?
List<DataClass> xmlList = new List<DataClass>();
This is my List, and I would like to put all the DataClass items between the range (3 - 7) in a new List.
这是我的列表,我想将范围 (3 - 7) 之间的所有 DataClass 项目放在一个新列表中。
What would be the most efficient way? A foreach loop that that count++ everytime untill he reaches the items between a the range and add those items to the new list?
最有效的方法是什么?每次计数++的foreach循环,直到他到达范围之间的项目并将这些项目添加到新列表?
采纳答案by LightStriker
The method you are seeking is GetRange:
您正在寻求的方法是GetRange:
List<int> i = new List<int>();
List<int> sublist = i.GetRange(3, 4);
var filesToDelete = files.ToList().GetRange(2, files.Length - 2);
From the summary:
从摘要:
// Summary:
// Creates a shallow copy of a range of elements in the source System.Collections.Generic.List<T>.
// Parameters:
// index:
// The zero-based System.Collections.Generic.List<T> index at which the range
// starts.
// count:
// The number of elements in the range.
回答by Matt Burland
List implements a CopyTomethod that lets you specify the start and number of elements to copy. I'd suggest using that.
List 实现了一种CopyTo方法,可让您指定要复制的元素的开始和数量。我建议使用那个。
回答by Clemens
回答by Hamed Naeemaei
in c# 8 you can use Range and Index instead of Linq take and skip :
在 c# 8 中,您可以使用 Range 和 Index 而不是 Linq take and skip :
Sample array:
样本数组:
string[] CountryList = { "USA", "France", "Japan", "Korea", "Germany", "China", "Armenia"};
To get this result (element 1,2,3) ==> France Japan Korea
1: Get a range of array or list:
得到这个结果(元素1,2,3)==>法国日本韩国
1:获取数组或列表的范围:
var NewList=CountryList[1..3]
2: Define Range object
2:定义Range对象
Range range = 1..3;
var NewList=CountryList[range])
3: Use Index Object
3:使用索引对象
Index startIndex = 1;
Index endIndex = 3;
var NewList=CountryList[startIndex..endIndex]

