Search code examples
c#.netlist.net-3.5sublist

How to Get a Sublist in C#


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


Solution

  • You want List::GetRange(firstIndex, count).

    // I have a List called list
    List sublist = list.GetRange(5, 5); // (gets elements 5,6,7,8,9)
    List anotherSublist = list.GetRange(0, 4); // gets elements 0,1,2,3)
    

    Is that what you're after?

    If you're looking to delete the sublist items from the original list, you can then do:

    // list is our original list
    // sublist is our (newly created) sublist built from GetRange()
    foreach (Type t in sublist)
    {
        list.Remove(t);
    }