How compare 2 string arrays with duplicate records

Viewed 496

I have 2 string arrays for example

string[] a = {"The", "Big", "Ant", "The"};
string[] b = {"Big", "Ant", "Ran" };

Here I am comparing two string[] (a may contains duplicate elements as well). How to get not matched elements while comparing a and b in b(with duplicates as well). In Linq Except i am not getting duplicate records. I need to get duplicates as well.

b = a.Except(b).ToArray();

Expected result is ("The" doesn't appear in b and "Run" is not in a)

{"The", "The", "Ran"}

Thanks

2 Answers

You can use,

var res = a.Where(x => !b.Contains(x)).ToArray();

UPDATE

List<string> res = a.ToList();
for(int i=0; i<b.Length; i++) {
   if (a.Contains(b[i]))
       res.Remove(b[i]);
    else
       res.Add(b[i]);
}

res => {"The","The","Ran"}

We can add two Where conditions and then just Concat two arrays:

string[] a = { "The", "Big", "Ant", "The" };
string[] b = { "Big", "Ant", "Ran" };

var res = a.Where(x => !b.Contains(x))
            .Concat(b.Where(b1 => !a.Contains(b1)));
Related