【问题标题】:How to get items in a specific range (3 - 7) from list?如何从列表中获取特定范围(3 - 7)中的项目?
【发布时间】:2012-10-30 14:55:48
【问题描述】:

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

List<DataClass> xmlList = new List<DataClass>();

这是我的列表,我想将范围 (3 - 7) 之间的所有 DataClass 项放入一个新列表中。

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

【问题讨论】:

标签: c# list


【解决方案1】:

你要找的方法是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?
【解决方案2】:

如果您出于某种原因不喜欢使用 GetRange 方法,也可以使用 LINQ 编写以下代码。

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

【讨论】:

  • 我建议您改用ToList 扩展名:List&lt;int&gt; copy = list.Skip(2).Take(5).ToList()。它基本上做同样的事情,但我发现它更适合 LINQ 表达式。
  • @MartinLiversage 请注意,这只是视觉上的差异,除非您处理的是匿名类型(在这种情况下,您需要 ToList)。在功能上两者几乎相同。
  • 请注意 List.GetRange 将更有效,但对于较大的集合:icodeit.wordpress.com/2012/08/27/…, geekswithblogs.net/BlackRabbitCoder/archive/2012/03/29/…
  • 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() 不会。
【解决方案3】:

在 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&lt;T&gt; 不支持新的范围语法。
  • @Chronicle 是的,你可以使用 List.ToArray()[range ]
【解决方案4】:

List 实现了一个CopyTo 方法,该方法允许您指定要复制的元素的开始和数量。我建议使用它。

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

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多