C # find a number common to two or more lists

What is the syntax for finding a list of numbers in two or more lists? I went in cycles when I needed to check only two lists, but now I need to make some ... Something like

List<int> commonIds = SELECT id from list1 where list1.contains(id), list2.contains(id), list3.contains(id) ... 
-1
source share
4 answers

Search for the intersection of any number of lists

If you want to find the set of numbers that exist in all lists, then Enumerable.Intersect is a good way to do this. You don’t even need to hardcode the collection of lists; you can create it at runtime:

 var lists = new[] { list1, list2, ..., listN }; // dynamically specified var common = lists.First().AsEnumerable(); foreach (var list in lists.Skip(1)) { common = common.Intersect(list); } // and now common has the result, eg var listOfCommonEntries = common.ToList(); 

Search for the union of intersections between the main list and each other

If you want to find a set that includes all the common numbers between list 1 and list 2, combine all the common numbers between list 1 and list N, and then change a few:

 var common = Enumerable.Empty<int>(); foreach (var list in lists.Skip(1)) { common = common.Union(lists.First().Intersect(list)); } 
+3
source

You can use Enumerable.Intersect :

 List<int> commonIds = list1.Intersect(list2.Intersect(list3)).ToList(); 

This is quite effective as it uses a set.

+2
source

Here is the function

it returns the union of the intersection of all two sets.

 public static IEnumerable<T> SharedItems<T>(this IEnumerable<IEnumerable<T>> source) { var pairs = from s1 in source from s2 in source select new { s1 , s2 }; var intersects = pairs .Where(p => p.s1 != p.s2) .Select(p => p.s1.Intersect(p.s2)); return intersects.SelectMany(i => i).Distinct(); } 
+1
source

for settings

 void Main() { List<int> one = new List<int>() {1, 3, 4, 6, 7}; List<int> second = new List<int>() {1, 2, 4, 5}; foreach(int r in one.Intersect(second)) Console.WriteLine(r); } 
-1
source

Source: https://habr.com/ru/post/986805/


All Articles