Search multiple values in one column

2019-09-04 05:13发布

问题:

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

回答1:

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


回答2:

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}", ...}))