CSharp examples for System.Collections.Generic:IEnumerable
Calculates the intersection set of two IEnumerable
/*// w ww . j ava 2 s.co m Copyright (C) 2007-2017 Team MediaPortal http://www.team-mediaportal.com This file is part of MediaPortal 2 MediaPortal 2 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MediaPortal 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MediaPortal 2. If not, see <http://www.gnu.org/licenses/>. */ using System.Linq; using System.Collections.Generic; using System.Collections; using System; public class Main{ /// <summary> /// Calculates the intersection set of <paramref name="c1"/> and <paramref name="c2"/> and returns it. /// If the type parameters of the collections differ, the collection with the more general element type /// must be used at the second position. /// </summary> /// <typeparam name="S">Element type of the first source collection. May be more specific than /// the type parameter of the second collection.</typeparam> /// <typeparam name="T">Element type of the second source collection and the result collection. /// May be more general than the type parameter of the first collection <see cref="S"/>.</typeparam> /// <param name="c1">First source collection.</param> /// <param name="c2">Second source collection</param> /// <returns>Intersection of <paramref name="c1"/> and <paramref name="c2"/>.</returns> public static ICollection<T> Intersection<S, T>(IEnumerable<S> c1, IEnumerable<T> c2) where S: T { ICollection<T> result = new List<T>(); ICollection<S> x1 = c1 as ICollection<S>; if (x1 != null) { // First argument implements ICollection<S> foreach (S s in c2) if (x1.Contains(s)) result.Add(s); } else { ICollection<T> x2 = c2 as ICollection<T> ?? new List<T>(c2); // If second argument also doesn't implement ICollection<T>, create a new list foreach (S s in c1) if (x2.Contains(s)) result.Add(s); } return result; } }