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

前端 未结 3 1815
野的像风
野的像风 2020-12-31 03:45

I have two arrays of strings:

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

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

I want

相关标签:
3条回答
  • 2020-12-31 04:25

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

    0 讨论(0)
  • 2020-12-31 04:28
    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.

    0 讨论(0)
  • 2020-12-31 04:30
    string[] result = all.Except<string>(taken).ToArray<string>();
    
    0 讨论(0)
提交回复
热议问题