-2

I have two lists with data as following examples

var listA = new[]{ "A", "B", "C", "D", "B", "E", "C", "F", "G"};
var listB = new[]{ "A", "B", "C", "E" };

listA can have duplicate values.

I need to find all items from listB which have unique values (non-duplicate only) in listA with LINQ or C#.

the expected result listC should be like

listC = {A, E};

I am using the following code

   var list = listA.GroupBy(x => x).All(g => g.Count() == 1);
   var listC = list.Except(listB).ToList();
  • 6
    This isn't a code writing service I'm afraid. Have you tried anything? Where did you get stuck? – DavidG Feb 18 '21 at 10:30
  • 1
    I give you the documentation to the needed functions: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct?view=net-5.0 and https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.intersect?view=net-5.0 – Isitar Feb 18 '21 at 10:32
  • @DavidG the dupe doesn´t really match I suppose. This question isn´t about finding dupes, but about finding those elements that don´t have dupes. – MakePeaceGreatAgain Feb 18 '21 at 10:42
  • @HimBromBeere Yeah, you're right. But the answer is a combo of two things, duplicates and intersection, so added some more links to the list. – DavidG Feb 18 '21 at 10:46

2 Answers2

0
  • You find elements which are not duplicate in their own set for each set.
  • Then, take intersection with the other set.

You can make use of contains() method since they are of type string.

0
var listA = new[]{ "A", "B", "C", "D", "B", "E", "C", "F", "G"};
var listB = new[]{ "A", "B", "C", "E" };
var listC = listB.Where(x=>listA.Where(y=>y==x).Count() == 1);        
foreach(var item in listC) Console.WriteLine(item);

The Simplest most naive solution I could think of. Smells like homework though.

B-Rad
  • 383
  • 1
  • 14