Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the quickest way to remove one array of items from another?

Tags:

arrays

c#

.net

I have two arrays of strings:

 string[] all = new string[]{"a", "b", "c", "d"}

 string[] taken = new string[]{"a", "b"}

I want to generate a new string array with c and d which is all - taken.

Any quick way in .net 3.5 to do this without a manual loop and creating new lists?

like image 641
leora Avatar asked Dec 10 '09 23:12

leora


People also ask

How do you remove one array from another array?

For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.

How can I remove a specific item from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you delete multiple objects from an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.


2 Answers

var remains = all.Except(taken);

Note that this does not return an array. But you need to ask yourself if you really need an array or if IEnumerable is more appropriate (hint: it almost always is). If you really need an array, you can just call .ToArray() to get it.

In this case, there may be a big performance advantage to not using an array right away. Consider you have "a" through "d" in your "all" collection, and "a" and "b" in your "taken" collection. At this point, the "remains" variable doesn't contain any data yet. Instead, it's an object that knows how to tell you what data will be there when you ask it. If you never actually need that variable, you never did any work to calculate what items belong in it.

like image 170
Joel Coehoorn Avatar answered Sep 28 '22 08:09

Joel Coehoorn


You are using LINQ Except for it, like all.Except(taken).

like image 29
Li0liQ Avatar answered Sep 28 '22 10:09

Li0liQ