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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:44:23  来源:igfitidea点击:

How to get items in a specific range (3 - 7) from list?

c#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方法,可让您指定要复制的元素的开始和数量。我建议使用那个。

See: http://msdn.microsoft.com/en-us/library/3eb2b9x8.aspx

请参阅:http: //msdn.microsoft.com/en-us/library/3eb2b9x8.aspx

回答by Clemens

If for any reason you don't like to use the GetRange method, you could also write the following using LINQ.

如果出于任何原因您不喜欢使用 GetRange 方法,您也可以使用LINQ编写以下内容。

List<int> list = ...
var subList = list.Skip(2).Take(5).ToList();

回答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]