user3140153
user3140153

Reputation: 47

To remove common string from two string array in .net

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"}

Upvotes: 1

Views: 1142

Answers (4)

Selman Genç
Selman Genç

Reputation: 101681

Also you can use Where with Contains

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

Upvotes: 0

Akanksha Gaur
Akanksha Gaur

Reputation: 2686

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();

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98750

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.

Upvotes: 1

Satpal
Satpal

Reputation: 133403

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;

Upvotes: 4

Related Questions