How to Get a Sublist in C#

前端 未结 6 1550
走了就别回头了
走了就别回头了 2021-02-02 05:09

I have a List and i need to take a sublist out of this list. Is there any methods of List available for this in .NET 3.5?

6条回答
  •  借酒劲吻你
    2021-02-02 05:13

    With LINQ:

    List l = new List { "1", "2", "3" ,"4","5"};
    List l2 = l.Skip(1).Take(2).ToList();
    

    If you need foreach, then no need for ToList:

    foreach (string s in l.Skip(1).Take(2)){}
    

    Advantage of LINQ is that if you want to just skip some leading element,you can :

    List l2 = l.Skip(1).ToList();
    foreach (string s in l.Skip(1)){}
    

    i.e. no need to take care of count/length, etc.

提交回复
热议问题