1

I have two string arrays -

            string[] One = new string[3];

            One[0] = "Pen";          
            One[1] = "Pencil";          
            One[2] = "card"; 

and,

            string[] Two = new string[2];

            Two[0] = "card";          
            Two[1] = "drive";      

Now, I want a new string array from these two, such that the final result does not contain any element of the Two array. i.e. it should have, "Pen", "Pencil" only.

  • Like Union method in c#, is there any similar method which can be used here ?? – Vishwas Joshi Feb 02 '20 at 10:41
  • 1
    Yes, you can use linq Except method. One.Except(Two).ToArray() – Lior Feb 02 '20 at 11:05
  • 2
    Does this answer your question? [How to perform set subtraction on arrays in C#?](https://stackoverflow.com/questions/5058609/how-to-perform-set-subtraction-on-arrays-in-c) – SᴇM Feb 02 '20 at 11:13

3 Answers3

5

This simple linq query can give you result.

var res = One.Except(Two);

Further, if in case you need to ignore case, use overload version of above method as:

var res = One.Except(Two, StringComparer.OrdinalIgnoreCase);

OR, Equivalently.

var res  = One.Where(x=>!Two.Contains(x)).ToArray();
Pashupati Khanal
  • 733
  • 3
  • 11
4

You can use Linq -

var res = One.Where(x => Two.Find(x) == null);

Or even better:

        string[] One = new string[3];

        One[0] = "Pen";
        One[1] = "Pencil";
        One[2] = "card";
        string[] Two = new string[2];

        Two[0] = "card";
        Two[1] = "drive";

        var res = One.Except(Two);
Dani Toker
  • 406
  • 6
  • 19
1

You need something like non-intersect

         string[] One = new string[3];

            One[0] = "Pen";          
            One[1] = "Pencil";          
            One[2] = "card";

        string[] Two = new string[2];

            Two[0] = "card";          
            Two[1] = "drive";

        var nonintersectOne = One.Except(Two);   
        foreach(var str in  nonintersectOne)
           Console.WriteLine(str);

        // Or if you want the non intersect from both
        var nonintersectBoth = One.Except(Two).Union(Two.Except(One)).ToArray();
        foreach(var str in  nonintersect)
           Console.WriteLine(str);

Output 1:

Pen

Pencil

Output 2:

Pen

Pencil

drive

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61