Search code examples
sqllinqrelational-division

What is LINQ operator to perform division operation on Tables?


To select elements belonging to a particular group in Table, if elements and their group type are contained in one table and all group types are listed in another table we perform division on tables. I am trying LINQ query to perform the same operation. Please tell me how can I do perform it?


Solution

  • Apparently from the definition of that blog post you'd want to intersect and except.

    Table1.Except(Table1.Intersect(Table2));
    

    or rather in your case I'd guess

    Table1.Where(d => !Table2.Any(t => t.Type == d.Type));
    

    not so hard.

    I don't think performance can be made much better, actually. Maybe with a groupby.

    Table1.GroupBy(t => t.Type).Where(g => !Table2.Any(t => t.Type == g.Key)).SelectMany(g => g);
    

    this should be better for performance. Only searches the second table for every kind of type once, not for every row in Table1.