How to Use Linq Contains(String[]) Instead of Contains(String)

How do I use LINQ Contains(string[]) instead of Contains(string)

spoulson has it nearly right, but you need to create a List<string> from string[] first. Actually a List<int> would be better if uid is also int. List<T> supports Contains(). Doing uid.ToString().Contains(string[]) would imply that the uid as a string contains all of the values of the array as a substring??? Even if you did write the extension method the sense of it would be wrong.

[EDIT]

Unless you changed it around and wrote it for string[] as Mitch Wheat demonstrates, then you'd just be able to skip the conversion step.

[ENDEDIT]

Here is what you want, if you don't do the extension method (unless you already have the collection of potential uids as ints -- then just use List<int>() instead). This uses the chained method syntax, which I think is cleaner, and
does the conversion to int to ensure that the query can be used with more providers.

var uids = arrayofuids.Select(id => int.Parse(id)).ToList();

var selected = table.Where(t => uids.Contains(t.uid));

LinQ WHERE string.Contains or string.IndexOf?


var result = collection.Where(item => stringsToCheck.Any(stringToCheck => 
item.Name.Contains(stringToCheck)));

Read in English this is: give me all of the items in the collection where, of all of the strings to check one of them is a substring of the string in the collection.

How i use Contains for string in Linq to Sql to match only the beginning of a word

You can check if the first word starts with the query by using StartsWith instead of Contains:

C.Name.StartsWith(Query)

This only checks the first word, not all words in the string.

You can't do a full text search directly using LINQ. What you can do instead is create a stored procedure to do the full text search and call that using LINQ.

Related question:

  • Is it possible to use Full Text Search (FTS) with LINQ?

See also:

  • LINQ to SQL - Enabling Fulltext searching

Using 'Contains' in linq query

You need to use a metric that tells you if your string match is "good enough". One such metric is the Levenshtein distance. You can calculate the distances between the input string and all the strings in your collection and then select those entries from the collection which have a distance that is low enough.

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

Linq Query using Contains and not contains

Unfortunately you can use local sequences only with Contains operator (which is translated into SQL IN operator). So, you can move whole filtering to memory

Rows = (from u in DB.Clients.AsEnumerable()
where u.Name.Contains(searchTerm) &&
!excludeTerms.Any(s => u.Name.Contains(s))
select new ClientModel {
Name = u.FullName,
Id = u.Id,
}).Take(5).ToList();

Or just filtering out excluded terms:

Rows = (from u in DB.Clients
where u.Name.Contains(searchTerm)
select new ClientModel {
Name = u.FullName,
Id = u.Id,
}).AsEnumerable()
.Where(m => !excludeTerms.Any(s => m.Name.Contains(s)))
.Take(5).ToList();

How can I use Linq to find items with matching words from a comma separated string?

You’re using a db it seems, so you need to remain mindful of what can and what cannot be converted into an SQL

You might find better success with something like:

var x = db.WebContentsImages;

foreach(string tag in queryTags.Split(','))
x = x.Where(t => (',' + t.Tags + ',').Contains(',' + tag + ',', StringComparison.CurrentCultureIgnoreCase));


var list = x.ToListAsync();

The repeated where will act cumulatively and hopefully generate a set of sql like:

SELECT * FROM table 
WHERE ','+tags+',' LIKE '%,red,%' AND
','+tags+',' LIKE '%,ball,%'

I should point out though that this is a fairly horrific way to store the data in the db and ask it to return things based on string LIKE.. tags should really have their own table and then a middleman table maps what Things have which Tags

You’re becoming confused with the current structure because string has a Contains method that returns true if a substring exists within this string, and Linq extends ienumerable collections to also have a different Contains method that tells whether a collection Contains a particular element. You’re mixing the two and asking string Contains to report on whether the string Contains an array etc. You need to be using the LINQ Contains all the time, which means splitting your Tags on comma and then asking if the resulting array of strings contains all of the array of strings resulting from splitting the queryTags on comma too

The problem is that while that can happen on the client I doubt your ORM will be able to carry out a split on the server side which means it will have to drag the entire db table down to the client. This is why I went the other way and converted everything to use String Contains in the hopes that it will become a bunch of LIKE AND on the server..

It would be better not to store the data this way

If Tags and queryTags were some kind of IEnumerable of string, you’d stand a better chance of saying

products.Where(
product => queryTags.All(queryTag => product.Tags.Contains(queryTag)
)

In English this is “for all products, filter to only products where all of the queryTags are present in the product.Tags list

You could manipulate your current data thus; make queryTags a string result from splitting the query string on comma, and rename your Tags csv string as TagsCsv and make a new property called Tags that returns TagsCsv.Split(',') but I wholly expect that it would have to be executed on the client, not in the db

var queryTags = “red,ball”.Split(',');

//horrific, for illustration purposes only
class Product{
String TagsCsv = “red,plastic,round,ball”;
String[] Tags { get { return TagsCsv.Split(',') } }
}

C# Linq where clause .Contains(string[])

Making it LINQ to Objects actually means it's easier to answer. I think you want something like:

from v in query.AsEnumerable()
let headers = v.Header36.Split(',')
where yy.BodyTypes.Intersect(headers).Any()
select new [...]

Note that your (from yy in BodyTypes select yy) is mostly equivalent to just BodyTypes (at least it will be given the way you're then using it) - you don't need to use a query expression every time you want to do anything.

Here's a slightly more efficient version:

HashSet<String> bodyTypes = new HashSet<String>(yy.BodyTypes);
var query = from v in query.AsEnumerable()
let headers = v.Header36.Split(',')
where bodyTypes.Overlaps(headers)
select new [...]

Contains functionality in Linq to XML Where Clause

Try this:

_filters.Any(s => ((string)sr.Element("itemtype") ?? "").Contains(s))

This way you're checking that the element's value contains any of the strings in _filters. The use of the null coalescing operator ensures a NullReferenceException isn't thrown when the itemtype node doesn't exist since it is replaced with an empty string.

The other approach is to use let and filter out the nulls:

var q = from sr in SearchResults.Descendants("Result")
let itemtype = (string)sr.Element("itemtype")
where itemtype != null &&
_filters.Any(filter => itemtype.Contains(filter))
orderby (string)sr.Element("ipitemtype") ascending
select new SearchItem
{
//Create Object
ID = (string)sr.Element("blabla")
}

Note that String.Contains is case sensitive. So a check for "videos" won't match on "Videos" with a capital "V". To ignore case you can use String.IndexOf in this manner:

_filters.Any(filter => itemtype.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) >= 0)

LINQ: Entity string field contains any of an array of strings

Since you want to see if search contains a word which is contained in the description of p you basically need to test for each value in search if it is contained in the description of p

result = from p in products
where search.Any(val => p.Description.Contains(val))
select p;

This is c# syntax for the lambda method since my vb is not that great



Related Topics



Leave a reply



Submit