tags:

views:

104

answers:

3

i have 2 string arrays:

 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 dotnet 3.5 to do this without a manual loop and creating new lists?

+7  A: 
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.

Joel Coehoorn
´result´ is not a string[], which the question requires.
CesarGon
Was just editing in a comment on that.
Joel Coehoorn
I just saw it, and removed my downvote. :-)
CesarGon
It's worth mentioning that a `ToArray()` call is all that's required if the OP does need an array.
LukeH
+4  A: 

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

Li0liQ
+2  A: 
string[] result = all.Except<string>(taken).ToArray<string>();
CesarGon
You don't have to state the type for the generic methods, the compiler is able to infer them.
Maximilian Mayerl
I am aware of that. :-) But I think that it's useful to write the full syntax when you teach others.
CesarGon