1

I have two string arrays (str and str1):

   string[] str = new string[] { "Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat" };
   string[] str1 = new string[] { "Mon", "Tues", "Wed" };
   string[] str2 = new string[10];

I want to create a new array which will contain the items that appears only in one of the arrays. The output will be:

str2[]={"Sun","Thur","Fri","Sat"}
0

4 Answers 4

4

You can use Enumerable.Except, it produces the set difference of two sequences by using the default equality comparer to compare values.

 var str2= str.Except(str1);

NOTE: Don't forget to add System.Linq namespace like;

using System.Linq;
1
  • 1
    @user3140153, Did you included System.Linq. See Soner Gönül has provided working demo
    – Satpal
    Dec 28, 2013 at 13:52
1

You can use Enumerable.Except method with LINQ. Don't forget to add System.Linq namespace. like;

Produces the set difference of two sequences by using the default equality comparer to compare values.

string[] str = new string[] { "Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat" };
string[] str1 = new string[] { "Mon", "Tues", "Wed" };

var str2 = str.Except(str1);

foreach (var i in str2)
{
   Console.WriteLine(i);
}

Output will be;

Sun
Thur
Fri
Sat

Here a demonstration.

1
1
string[] str = new string[] { "Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat" };
string[] str1 = new string[] { "Mon", "Tues", "Wed" };

var str2 = str.Where(t => !str1.Contains(t)).ToArray();
0

Also you can use Where with Contains

var str2 = str.Where(s => !(str1.Contains(s)).Select(s => s);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.