user3298493
user3298493

Reputation: 41

Conditional Addition of elements in to a list in C#

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

Answers (2)

Jon Skeet
Jon Skeet

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

lc.
lc.

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

Related Questions