0

I want to remove items of a Jagged array using indizes.

int[] toRemove; (e.g, {0, 1})

int[][] MainArray (e.g. { [0] {...}, [1] {...}, [2] {...}}

Expected result

int[][] result (e.g. {[2] {...}}

From the MainArray how to remove the items which having indexes from the toRemove list?

Is there an efficient way using LINQ?

2
  • 1
    Linq is a query facility, it doesn't directly remove items (though you can query a sub-set and assign it back to the original) Commented Mar 22, 2012 at 13:59
  • You cannot remove from an array, you understand you will get a new array? And does that have to be an array again? Commented Mar 22, 2012 at 14:13

2 Answers 2

3

Hopefully this gives the expected result:

var notInToRemove = MainArray
    .Where((arr ,index) => !toRemove.Contains(index)).ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

Now I know why Where method has an overload with the int Index parmeter ;-)
Thanks Tim. Great support. Works as expected and as I needed. LINQ is so elegant, but hard learning :-(. By the way, I also studied in Aachen. Nice to know you.
@Suresh: ... and i'm still living and working here, i'm happy to hear that it works :) LINQ is hard at the beginning because it compresses complexity and you often need to think laterally. But the result is almost always more comprehensible. Find the way to the corect result in mind and then begin to write the query, not vice-versa.
0

You could use the ElementAt method instead of the Remove method if all you want is the data that is not to be there in the toRemove set.

int[] toRemove = {0,1};
int[][] mainArray = new int[3][];
mainArray[0] = new int[]{0,0,0};
mainArray[1] = new int[]{1,1,1};
mainArray[2] = new int[]{2,2,2};

var result = mainArray.ElementAt(2); // This value 2 is found as all indexes of mainArray except the values in toRemove
//(Code would look like this : 
Enumerable.Range(0, mainArray.Length).Except(toRemove);

Comments

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.