How to Get a Sublist in C#

Thomas Manalil picture Thomas Manalil · Nov 11, 2009 · Viewed 98.8k times · Source

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?

Answer

Josh picture Josh · Nov 11, 2009

You want List::GetRange(firstIndex, count). See http://msdn.microsoft.com/en-us/library/21k0e39c.aspx

// 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);
}