How to write a ContainsAll query using LINQ? (C# L

2019-07-19 04:19发布

问题:

This question already has an answer here:

  • Determine if a sequence contains all elements of another sequence using Linq [duplicate] 4 answers

Suppose i have the following

var mustHave = new int [] { 1, 2 }

and a table named db.Numbers

public class Number
{
     public int id;
     public int number;
}

populated with

Numbers.add(new Number(){id=8,number=1});
Numbers.add(new Number(){id=8,number=2});
Numbers.add(new Number(){id=8,number=3});
Numbers.add(new Number(){id=9,number=1});
Numbers.add(new Number(){id=9,number=3});

I want to get all ids which are associated to all numbers in the mustHave variable. For example The query must return id=8 but not id=9. The real case is much more complicated and does the query against a database with Linq-To-Sql.

回答1:

Try this:

var numbers = Numbers.FindAll(n=>n.id=8);
var mustHave= new int[numbers.Count][2];
int counter = 0;`
foreach(var number in numbers)
{
    mustHave[counter][0]=number.id;
    mustHave[counter][1]=number.number;
    counter++;
 }


回答2:

Well if you're doing something in LINQtoSQL with a DataContext, try this:

var mustHave = new int [] { 1, 2 };
var items = 
  from x in DataContext.SomeTable
  where mustHave.Contains(x.SomeProperty)
  select x;