Search code examples
c#.netlinq.net-6.0

.NET 6 IntersectBy and ExceptBy examples


Could someone provide me a small example on how to Use the .NET 6 LINQ IntersectBy and ExceptBy methods? MSDN hasn't got any examples and the one I tried doesn't compile due to CS0411 error. The example I tried:

namespace Test
{
    internal struct Example
    {
        public int X { get; set; }
        public int Y { get; set; }

        public override string ToString()
        {
            return $"{X}, {Y}";
        }
    }

    public class Program
    {
        public static void Main()
        {
            var elements = new List<Example>
            {
                new Example { X = 10, Y = 20 },
                new Example { X = 11, Y = 23 },
            };

            var elements2 = new List<Example>
            {
                new Example { X = 10, Y = 12 },
                new Example { X = 44, Y = 20 },
            };


            //ok
            var union = elements.UnionBy(elements2, x => x.X);
            
            //CS0411 - Why ?
            var intersect = elements.IntersectBy(elements2, x => x.X);

            //CS0411 - Why ?
            var except = elements.ExceptBy(elements2, x => x.X);

            Console.ReadKey();
        }
    }
}

Solution

  • Granted the documentation doesn't have any examples, it states that the selector function should select TKey i.e. the type of the second collection. The following should work:

    var intersect = elements.IntersectBy(elements2, x => x);
    var except = elements.ExceptBy(elements2, x => x);
    

    Although I think this may be closer to what you want:

    var intersect = elements.IntersectBy(elements2.Select(e => e.X), x => x.X);
    

    For more complex types, you may want to consider implementing an IEqualityComparer and using the overloads that take one as an argument.