tags:

views:

50

answers:

2

I'm trying to figure out how to do this, and I"m stumped. I'm sure it's something simple that I'm just missing.

Say I have a table that is a collection of names, and I want to check if a subset of those names exist like this:

var names = new List{ "John", "Steven", "Mary"};
var dbNames = from n in Db.Names
              where n.FirstName == //names ???;

Is there anyway to do this?

Thanks!

+1  A: 
where names.Contains(n.FirstName)

Although you have to watch the types you call this on -- some of the Contains methods won't get translated to LINQ-to-SQL. You might need to cast it to IEnumerable or IQueryable first, or something.

MichaelGG
+1  A: 

If you are looking to see if the entire set exists in your database, you should use Intersect().

var names = new List<string> { "John", "Steven", "Mary" };
var dbNames = Db.Names.Select( n => n.FirstName)
                      .Distinct();
bool isSubset = dbNames.Intersect( names ).Count() == names.Count;

You want the size of the intersection to be the same size as the second set. If that's the case then the second set is a subset of the first.

tvanfosson