Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find duplicate in a list from a reference list

Tags:

c#

.net

linq

c#-4.0

I'd like know if at least one element of listRef is present more than once in listA ? The other values can be present more than once.

List<string> listA = new List<string> { "A", "A", "B", "C", "D", "E" };
List<string> listRef = new List<string> { "B", "D" };

Thanks,

like image 632
Kris-I Avatar asked Dec 09 '22 13:12

Kris-I


2 Answers

Try this:

bool hasRef = listref.Any(r => listA.Count(a => a == r) > 1);
like image 78
mattytommo Avatar answered Dec 11 '22 03:12

mattytommo


I would use ToLookup method to generate Lookup<string, string> first, and then use it to check your condition:

var lookup = listA.ToLookup(x => x);
return listRef.Any(x => lookup.Contains(x) && lookup[x].Count() > 1);

You could use GroupBy and ToDictionary to achieve the same:

var groups = listA.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
return listRef.Any(x => groups.ContainsKey(x) && groups[x] > 1);
like image 37
MarcinJuraszek Avatar answered Dec 11 '22 03:12

MarcinJuraszek