C# 獲取List集合中指定幾行的數據

最近在做一個項目需要獲取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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章