最近在做一个项目需要获取list集合中指定几行的数据,如何快速获取。
#region 构造方法(Start)
/// <summary>
/// 构造方法
/// </summary>
public class MonthClass
{
public string Id { get; set; }
public string Text { get; set; }
}
#endregion 构造方法(End)
List<MonthClass> list=new List<MonthClass> ();
MonthClass model=new MonthClass();
model.Id ="1";
model.Text ="1";
list.add(model)
MonthClass model1=new MonthClass();
model1.Id ="2";
model1.Text ="2";
list.add(model1)
MonthClass model2=new MonthClass();
model2.Id ="3";
model2.Text ="3";
list.add(model2)
MonthClass model=new MonthClass();
model3.Id ="4";
model3.Text ="4";
list.add(model3)
上面构造了一个集合:list.count=4
解决问题:想要获取list集合中的下标为1至3的数据也就是(list[1]、list[2]、list[3])
List<MonthClass> list2 = list.GetRange(1, 3);
如上就解决了取值的问题。
解释:
//
// 摘要:
// 创建源 System.Collections.Generic.List`1 中的元素范围的浅表副本。
//
// 参数:
// index:
// 范围开始处的从零开始的 System.Collections.Generic.List`1 索引。
//
// count:
// 范围中的元素数。
//
// 返回结果:
// 源 System.Collections.Generic.List`1 中的元素范围的浅表副本。
//
// 异常:
// T:System.ArgumentOutOfRangeException:
// index 小于 0。- 或 -count 小于 0。
//
// T:System.ArgumentException:
// index 和 count 不表示 System.Collections.Generic.List`1 中元素的有效范围。
public List<T> GetRange(int index, int count);
通俗的讲:
public List<T> GetRange(int index, int count);
index:表示获取list集合中的第几个数据。(说明list集合是从0开始的)
count:是需要往后面取几个数据(包括开始的那个数据)
GetRange(5, 5);
说明:获取list集合下标是5的数据,往后面在获取5个数据
结果(list[5]、list[6]、list[7]、list[8]、list[9])
GetRange(7, 8);
说明:获取list集合下标是5的数据,往后面在获取5个数据
结果(list[7]、list[8]、list[9]、list[10]、list[11]、list[12]、list[13]、list[14])
这样的解释还是可以的吧!!!!!!
C#中List集合使用GetRange方法获取指定索引范围内的所有值
在C#的List集合中有时候需要获取指定索引位置范围的元素对象来组成一个新的List集合,此时就可使用到List集合的扩展方法GetRange方法,GetRange方法专门用于获取List集合指定范围内的所有值,GetRange方法签名为List<T> GetRange(int index, int count),index为开始索引位置,count为从index开始获取元素的个数。
例如有个List<int>的集合list1,内部存储10个数字,需要获取list1集合从第5个数开始,连续的5个元素组成新的集合,可使用下列语句:
List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var resultList= list1.GetRange(4, 5);
计算结果为,resultList集合的元素为5,6,7,8,9