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.

3
  • Like Union method in c#, is there any similar method which can be used here ?? Commented Feb 2, 2020 at 10:41
  • 1
    Yes, you can use linq Except method. One.Except(Two).ToArray() Commented Feb 2, 2020 at 11:05
  • 2
    Does this answer your question? How to perform set subtraction on arrays in C#? Commented Feb 2, 2020 at 11:13

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

This is one of the easy way using linq. If you want to ignore case, then you can use the overloaded method: "One.Except(Two, StringComparer.OrdinalIgnoreCase)"
Thanks for your ans I will Update It as well.
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);

Comments

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

2 Comments

Quite right, updated accordingly. Leaving the secondary solution for anyone who might want it.
Please don't make the answer confusing by adding in superfluous content.

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.