-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);
4

1 回答 1

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

如果您的字符串列表是唯一的,请使用可以使用HashSet<>而不是List<>. 我认为它会给你更好的表现。

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

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

编辑:+1 向 Alexei Levenkov 指出 -Exists会导致问题,应该Contains改用。此外,验证生成的相同查询List以及HashSet如果您想在服务器上查询,无论您使用List还是HashSet.

生成的查询将类似于。

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

但是,假设specialID是局部变量,它将生成类似于上面的动态查询,但也会将其值传递给 SQL Server。此查询使用sp_executesql.

于 2013-06-15T00:58:12.053 回答