Search multiple values in one column

2019-09-04 05:06发布

How to select record based on multiple values search in one column using linq query. like product id is "product1", "product2","product3" n number of values we have

2条回答
迷人小祖宗
2楼-- · 2019-09-04 05:37

You could use something like (this is VB.Net, change to C# if necessary)

Dim result = products.Where(Function(p) p.ID = "product1" Or p.ID = "product2" Or p.ID = "product3", ...)

Alternatively, you could pull it all back to the client and use .Contains, like so:

Dim materializedProducts = products.ToList()
Dim result = materializedProducts.Where(Function(p) {"product1", "product2", "{product3}", ...}.Contains(p.ID))

Going further still, you could create an extension method (generic, if that floats your boat) called IsIn or similar that allows you to swap the order of the collection and the search value:

<Extension()> 
Public Function IsIn(Of T)(ByVal searchValue As T, 
                             ByVal searchSet As IEnumerable(Of T))
    Return searchset.Contains(searchValue)
End Sub


Dim materializedProducts = products.ToList()
Dim result = materializedProducts.Where(Function(p) p.ID.IsIn({"product1", "product2", "{product3}", ...}))
查看更多
放荡不羁爱自由
3楼-- · 2019-09-04 05:46

You can use the .Contains method to check whether a value is within a list.

var values = new List<string>() { "Prod1", "Prod2", "Prod3" };
var query = context.Set<Product>().Where(x => values.Contains(x.Name));
查看更多
登录 后发表回答