5

I have this method:

public void Foo(double[] values1, double[] values2, int[] indexes)
{
    var values1AtIndexes = new List<double>();
    var values1NotAtIndexes = new List<double>();
    var values2AtIndexes = new List<double>();
    var values2NotAtIndexes = new List<double>();

    for (int i = 0; i < values1.Length; i++)
    {
        if (indexes.Contains(i))
        {
            values1AtIndexes.Add(values1[i]);
            values2AtIndexes.Add(values2[i]);
        }
        else
        {
            values1NotAtIndexes.Add(values1[i]);
            values2NotAtIndexes.Add(values2[i]);
        }
    }
}

And I was wondering if there is a LINQ-way to this?

0

1 Answer 1

7

It could look like that (not looking at perf).

So I'm not sure that it's shorter, or easier to understand.

values1AtIndexes = values1.Where((m, index) => indexes.Contains(index)).ToList();
values2AtIndexes = values2.Where((m, index) => indexes.Contains(index)).ToList();
//alternative
values1AtIndexes = indexes.Select(m => values1[m]).ToList();
values1AtIndexes = indexes.Select(m => values2[m]).ToList();


//might be wrong if your lists contain duplicated values
values1NotAtIndexes = values1.Except(values1AtIndexes).ToList();
values2NotAtIndexes = values2.Except(values2AtIndexes).ToList();

As you pointed, Except might give you wrong results if you have duplicates.

So if you know you can have duplicates, you should rather do

values1NotAtIndexes = values1.Where((m, index) => !indexes.Contains(index)).ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

I think there might be a problem with the Except since it's not certain that there are no duplicate doubles in the source arrays.
I will mark this as the accepted answer, but as you stated, in terms of performance my approach will probably be better, because i am only iterating 1 time instead of 4 times.
@metacircle Indeed (well, you need "big" lists to see any difference, but yes). And the goal of the method is also clearer !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.