【发布时间】:2012-10-30 14:55:48
【问题描述】:
从列表中选择特定范围内的所有项目并将其放入新列表中的最有效方法是什么?
List<DataClass> xmlList = new List<DataClass>();
这是我的列表,我想将范围 (3 - 7) 之间的所有 DataClass 项放入一个新列表中。
什么是最有效的方法?每次计数 ++ 的 foreach 循环,直到他到达范围之间的项目并将这些项目添加到新列表中?
【问题讨论】:
从列表中选择特定范围内的所有项目并将其放入新列表中的最有效方法是什么?
List<DataClass> xmlList = new List<DataClass>();
这是我的列表,我想将范围 (3 - 7) 之间的所有 DataClass 项放入一个新列表中。
什么是最有效的方法?每次计数 ++ 的 foreach 循环,直到他到达范围之间的项目并将这些项目添加到新列表中?
【问题讨论】:
你要找的方法是GetRange:
List<int> i = new List<int>();
List<int> sublist = i.GetRange(3, 4);
var filesToDelete = files.ToList().GetRange(2, files.Length - 2);
摘自:
// 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(3, 5); 以便获得索引 3、4、5、6、7?
如果您出于某种原因不喜欢使用 GetRange 方法,也可以使用 LINQ 编写以下代码。
List<int> list = ...
var subList = list.Skip(2).Take(5).ToList();
【讨论】:
ToList 扩展名:List<int> copy = list.Skip(2).Take(5).ToList()。它基本上做同样的事情,但我发现它更适合 LINQ 表达式。
ToList)。在功能上两者几乎相同。
GetRange() 可以抛出 ArgumentException (Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection),而 Skip().Take() 不会。
在 c# 8 中,您可以使用 Range 和 Index 而不是 Linq take and skip :
示例数组:
string[] CountryList = { "USA", "France", "Japan", "Korea", "Germany", "China", "Armenia"};
要得到这个结果(元素 1,2,3)==> 法国 日本 韩国
1:获取一个范围的数组或列表:
var NewList=CountryList[1..3]
2:定义 Range 对象
Range range = 1..3;
var NewList=CountryList[range])
3:使用索引对象
Index startIndex = 1;
Index endIndex = 3;
var NewList=CountryList[startIndex..endIndex]
【讨论】:
List<T> 不支持新的范围语法。
List 实现了一个CopyTo 方法,该方法允许您指定要复制的元素的开始和数量。我建议使用它。
【讨论】: