Jimmy
Jimmy

Reputation: 3264

Modify elements in a list by index

I need to modify a List<int> by indexes. I have the indexes in another List<int>

List<int> values;
List<int> indexes;

indexes.Select(i=>values[i]).ForEach(val=>val = 0);

Of course, I know the above syntax wont work. However, as I know the indexes of the items that I need to modify, I would like to to modify the list with the indexes with lambda. Is it possible to do that?

Upvotes: 3

Views: 9646

Answers (3)

Tomas Petricek
Tomas Petricek

Reputation: 243041

In some cases, LINQ isn't going to give you a particularly better solution, especially when working with indices or when modifying data. I think the following simple foreach loop will be probably the most readable way to write this:

foreach(var i in indexes) values[i] = 0;

However, if the collection indexes is of type List<T> then you can use the ForEach method (see MSDN). This makes the code a little shorter, but it is a question whether it is more readable than simple foreach loop:

indexes.ForEach(i => values[i] = 0);

ForEach method is not currently available in LINQ (for general IEnumerable<T>), but there are quite a few people asking for it. But as I said, it is not clear whether it makes code more readable or not.

(If you wanted to write the same thing for IEnumerable<T> you'd have to either use ToList or write your own ForEach extension method).

Upvotes: 6

Colin Mackay
Colin Mackay

Reputation: 19175

You don't have to use LINQ. You could do something as simple as this. It also keeps the meaning clearer, I think.

foreach(int index in indexes)
{
    values[index] = 0;
}

Upvotes: 1

tbridge
tbridge

Reputation: 1804

I might be missing something, but is this all you are looking for?

foreach(int index in indexes)
{
    values[index] = 0; // your modified value here
}

Upvotes: 1

Related Questions