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

1 Comment

@user3140153, Did you included System.Linq. See Soner Gönül has provided working demo
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 Comment

@user3140153 You are quite welcome. If one of these answers solved your problem, please consider to accept one meta.stackexchange.com/questions/5234/…
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();

Comments

0

Also you can use Where with Contains

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

Comments

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.