If the second list is large and may contain duplicates, I would use HashSet<string>
and IntersectWith
to remove possible duplicates and strings
that are not in the first list from the second:
var refSet = new HashSet<string>(listRef); refSet.IntersectWith(listA); bool anyMoreThanOne = refSet.Any(rs => listA.ContainsMoreThanOnce(rs, StringComparison.OrdinalIgnoreCase));
Here's an extension that is not very elegant but works:
public static bool ContainsMoreThanOnce(this IEnumerable<string> coll, String value, StringComparison comparer) { if (coll == null) throw new ArgumentNullException("col"); bool contains = false; foreach (string str in coll) { if (String.Compare(value, str, comparer) == 0) { if (contains) return true; else contains = true; } } return false; }
Demo
However, if the second listRef
is small or does not contain duplicates, you can simply use:
bool anyMoreThanOne = listRef .Any(rs => listA.ContainsMoreThanOnce(rs, StringComparison.OrdinalIgnoreCase));
source share