Reputation: 2687
I have a List<decimal>
and I want to create a new List<decimal>
from a subset of the first List.
Code example:
List<decimal> set1 = new List<decimal>() { 10, 20, 30, 40, 50 };
How do I create a new List that is from index=2 to index=4 (30, 40, 50)?
Upvotes: 1
Views: 97
Reputation: 23087
Using GetRange
var newlist = set1.GetRange(2,3);
You are passing starting index (2) and number of items you will get (3)
Upvotes: 3
Reputation: 223287
var list = set1.Select((r, i) => new { Index = i, Value = r })
.Where(t => t.Index >= 2 && t.Index <= 4)
.Select(r => r.Value);
If you want to have a List you can append ToList
to the query.
For output
foreach (var item in list)
{
Console.WriteLine(item);
}
output:
30
40
50
Upvotes: 3