notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

Creating a List from another List, filtered by certain indexes

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

Answers (3)

Kamil Budziewski
Kamil Budziewski

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

Habib
Habib

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

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

var set2 = set1.Skip(2).Take(3).ToList();

Upvotes: 3

Related Questions