Reputation: 43
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.
Upvotes: 1
Views: 1420
Reputation: 743
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();
Upvotes: 5
Reputation: 26362
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
Upvotes: 1
Reputation: 425
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);
Upvotes: 4