Reputation: 2742
I have a list of lists that contain some numbers. I wish to construct an output list of the second index element in each of these lists. I am able to achieve this using a normal loop, but was wondering how it would be possible to achieve the same thing using LINQ?
My current example:
List<int> output = new List<int>();
foreach (List<int> list in Data)
output.Add(list[2]);
Upvotes: 1
Views: 58
Reputation: 78535
You can use .Select
. I would also put a check in to ensure the number expected actually exists:
var results = Data.Where(d => d.Count > 2).Select(d => d.list[2]);
Upvotes: 1
Reputation: 171178
var output = Data.Select(list => list[2]).ToList();
This is a direct translation. I think it is much preferable to the manually written loop because it is less redundant and composes well.
Upvotes: 4