-1

I have a List property of type string. I would like to search my database to make sure that the list matches the results. For example:

List<string>strings = new List<string>({"test1","test2","etc"});

I would now like to do a search in my database using linq to check if under certain condition that these strings exist.

_databaseContext.Names.Where(x=>x.name == strings && specialID == 1);
John Saunders
  • 160,644
  • 26
  • 247
  • 397
user516883
  • 8,868
  • 23
  • 72
  • 114

1 Answers1

2
_databaseContext.Names.Where(x => strings.Contains(x.name) && specialID == 1);

If your list of strings is unique, use can use HashSet<> instead of List<>. I think it will give you better performance.

HashSet<string> hs = new HashSet<string> { "test1", "test2", "etc" };

_databaseContext.Names.Where(x => hs.Contains(x.name) && specialID == 1);

EDIT: +1 to Alexei Levenkov for pointing out- Exists will cause problems, should use Contains instead. Also, verified the same query generated for List as well as HashSet so in case you want to query on server, is does not matter whether you use Listor HashSet.

Generated query will be some thing like.

Select [name], [other columns]
From Names
Where [name] IN (N'test1', N'test2', N'etc')

However, assuming specialID is local variable, it will generate a dynamic query similar to above but also pass its value to SQL Server. This query is executed using sp_executesql.

YK1
  • 7,327
  • 1
  • 21
  • 28