I'm constructing a linq query that will check is a string in the DB contains any of the strings in a list of strings.
Something like.
query = query.Where(x => x.tags .Contains(--any of the items in my list of strings--));
I'd also like to know how many of the items in the list were matched.
Any help would be appreciated.
Update: I should have mentioned that tags is a string not a list. And I am adding on a couple more wheres that are not related to tags before the query actually runs. This is running against entity framework.
The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false. There Contains method in C# is implemented in two different namespaces as shown in the below image.
LINQ Contains is quantifier operator. In LINQ Contains it also checks with the data sources, to check whether the collection of lists contains their desired element or not, and then it returns the result as either true or false based on the expected outcomes of the result.
The SQL LIKE operator can also be used directly from LINQ by calling Telerik.OpenAccess.ExtensionMethods:Matches (this string src, string pattern) or System.Data.Linq.SqlClient.SqlMethods:Like (string src, string pattern). The former translates the * and ? wildcards into % and _, the latter doesn’t do such a translation. LINQ: … .
The question has mentioned that the use of Linq must be considered in the workaround. So using Linq the string array can apply the Contains method. Perhaps you should test your code - the IEnumerable<string>.Contains method does not have an overload that takes a lambda. Your code would not compile.
I've done something like this before:
var myList = new List<string>(); myList.Add("One"); myList.Add("Two"); var matches = query.Where(x => myList.Any(y => x.tags.Contains(y)));
EDIT: This answer assumed that tags
was a collection of strings...
It sounds like you might want:
var list = new List<string> { ... }; var query = query.Where(x => x.tags.Any(tag => list.Contains(tag));
Or:
var list = new List<string> { ... }; var query = query.Where(x => x.tags.Intersect(list).Any());
(If this is using LINQ to SQL or EF, you may find one works but the other doesn't. In just LINQ to Objects, both should work.)
To get the count, you'd need something like:
var result = query.Select(x => new { x, count = x.tags.Count(tag => list.Contains(tag)) }) .Where(pair => pair.count != 0);
Then each element of result
is a pair of x
(the item) and count
(the number of matching tags).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With