Reputation: 41
I have a multi-dimensional array of double dSet[,]
where each row has 1500 elements. I have a List<int> index
, with say 100 integers of values (0 - 1499) . Now, I have to create a List<double> val
with 100 elements, where each element is dSet[0,i], where i is an element of List<int> index
. I know that it can be done easily using a simple loop. I was wondering whether it can be done using a single statement using LinQ in C#.
EDIT: Thanks for the answers. Sorry but I forgot to mention that dSet is passed as ref :(. Can it be done now ?
Upvotes: 2
Views: 127
Reputation: 1500215
Sure - that's just a projection from each element of the index:
List<double> val = index.Select(i => dSet[0, i]).ToList();
Any time you've got something along the lines of "for each element from source, do something to get an output value based on that element", that's likely to end up as source.Select(...)
where the ...
is an expression of the "do something to get an output value based on that element".
The ToList()
just converts the result (an IEnumerable<double>
) into a List<double>
.
Upvotes: 3
Reputation: 116458
Seems like this is what you're looking for:
index.Select(i => dSet[0, i]).ToList();
The key is to select into your index
list, selecting a single value from dSet
for each value in the list.
Upvotes: 3