Reputation: 3256
I have following code:
public static void Main (string[] args) {
string word1 = "AN";
string word2 = "ANN";
//First try:
var intersect = word1.Intersect(word2);
var unCommon1 = word1.Except(intersect).Union(word2.Except(intersect));
//Second try:
var unCommon = word1.Except(word2).Union(word2.Except(word1));
}
Result I am trying to get is N
. I tried few ways to get it by reading online posts, I am unable to figure it out. Is there a way to get uncommon character between two strings using linq.
Order of characters in string does not matter. Here are few more scenarios: FOO & BAR will result in F,O,O,B,A,R. ANN & NAN will result in empty string.
Upvotes: 1
Views: 2220
Reputation: 1150
Here's a straight forward LINQ function.
string word1 = "AN";
string word2 = "ANN";
//get all the characters in both strings
var group = string.Concat(word1, word2)
//remove duplicates
.Distinct()
//count the times each character appears in word1 and word2, find the
//difference, and repeat the character difference times
.SelectMany(i => Enumerable.Repeat(i, Math.Abs(
word1.Count(j => j == i) -
word2.Count(j => j == i))));
Upvotes: 2