Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从列表中获取特定范围(3-7)内的项目?_C#_List - Fatal编程技术网

C# 如何从列表中获取特定范围(3-7)内的项目?

C# 如何从列表中获取特定范围(3-7)内的项目?,c#,list,C#,List,从列表中选择特定范围内的所有项目并将其放入新项目的最有效方法是什么 List<DataClass> xmlList = new List<DataClass>(); 这是我的列表,我想把范围在3-7之间的所有DataClass项放在一个新列表中 最有效的方法是什么?foreach循环每次计数+,直到到达范围内的项目并将这些项目添加到新列表?列表实现CopyTo方法,允许您指定要复制的元素的开始和数量。我建议用这个 请参阅:您正在寻找的方法是: 总结如下: // Summ

从列表中选择特定范围内的所有项目并将其放入新项目的最有效方法是什么

List<DataClass> xmlList = new List<DataClass>();
这是我的列表,我想把范围在3-7之间的所有DataClass项放在一个新列表中

最有效的方法是什么?foreach循环每次计数+,直到到达范围内的项目并将这些项目添加到新列表?

列表实现CopyTo方法,允许您指定要复制的元素的开始和数量。我建议用这个


请参阅:

您正在寻找的方法是:

总结如下:

// 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.

如果出于任何原因,您不喜欢使用GetRange方法,那么您也可以使用


在c 8中,您可以使用范围和索引,而不是Linq take和skip:

示例阵列:

要获得此结果元素1,2,3==>法国日本韩国

1:获取数组或列表的范围:

2:定义范围对象

3:使用索引对象


我建议您改用ToList扩展名:List copy=List.Skip2.Take5.ToList。它基本上是做同样的事情,但我发现它更适合LINQ表达式。@MartinLiversage注意,这只是视觉上的差异,除非您处理的是匿名类型,在这种情况下,您需要ToList。从功能上讲,这两种方法实际上是相同的。请注意,对于较大的集合,List.GetRange将更有效:,GetRange可以抛出ArgumentException Offset,并且数组的长度超出了范围,或者计数大于从索引到源集合结尾的元素数,而Skip.Take不会。列表的可能副本不支持新的范围语法。@编年史是的,您可以使用List.ToArray[range]
// 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.
List<int> list = ...
var subList = list.Skip(2).Take(5).ToList();
string[] CountryList = { "USA", "France", "Japan", "Korea", "Germany", "China", "Armenia"};  
   var NewList=CountryList[1..3]
Range range = 1..3;  
    var NewList=CountryList[range])
Index startIndex = 1;  
Index endIndex = 3;  
var NewList=CountryList[startIndex..endIndex]