I would like to create a list variable of items from another list. So lets say I have a list of 100 items I would like to pull items 25 - 35 and put them inside of another list. is there a way of doing this without calling a big for statement and pulling out the element one by one and putting that into a list.
Asked
Active
Viewed 1,475 times
3 Answers
10
you can use .Skip and .Take from System.Linq ....
Like this:
var result = myList.Skip(24).Take(10);
and if you need use ToList on the result to get another list
Random Dev
- 50,967
- 9
- 90
- 116
2
For a List<T>, you can use the GetRange Method.
Creates a shallow copy of a range of elements in the source List(Of T).
Do note that the second argument represents the count of elements in the range, not the end-index of the range.
Since you mention ArrayList, I should point out that while it too has a GetRange, method, the type is considered essentially legacy since .NET 2.0.
Ani
- 107,182
- 23
- 252
- 300
1
Use both Take and Skip
var newList = oldList.Skip(25).Take(10);
jose
- 2,685
- 4
- 36
- 48
-
that will skip one element to much – Random Dev Feb 28 '12 at 14:45