Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains particular characters in any order

Tags:

c#

.net

linq

The best way that I can explain what I'm trying to do is by giving an example:

I have a string StackOverflow in my database and when a user types OAW I would like to return that string and any other word that contains those three characters in any order.

I've tried playing with various LINQ/Lambda expressions but to no avail.

query.Where(a => a.SerialNumber.Contains(a));

I found a post here on SO that looks similar to mine but it's in Java.

I feel what I'm trying to do is extremely simple to implement but I'm just missing it. Any help will be greatly appreciated.

like image 917
HiTech Avatar asked Apr 22 '15 21:04

HiTech


People also ask

How do you check if a string contains a substring in any order?

Similar to the includes() method, the JavaScript indexOf() method checks if a string includes a substring. The general syntax for the indexOf() method looks something similar to this: string. indexOf(substring, index);

How do I check if a string contains a specific character?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.

How do you check if a particular character is present in a string JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.

How do I find a specific character in a string in Java?

To locate a character in a string, use the indexOf() method.

How do you check if a string contains a specific character in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .


2 Answers

You could try something like this:

query.Where(str => value.All(str.SerialNumber.Contains));

Here for any word in your database, you check if all the characters of the value, OAW, -Using the All extension method- are contained in the str.SerialNumber.

Update

This

str.SerialNumber.Contains

is equivalent to this lambda expression:

x => str.SerialNumber.Contains(x)

The x refers to the random element of the sequence in which we apply the All. In other words to the random character of value.

like image 93
Christos Avatar answered Oct 04 '22 20:10

Christos


You can use a ContainsAll type of function.

public static bool ContainsAllItems(IEnumerable<T> a, IEnumerable<T> b)
{
    return !b.Except(a).Any();
}

NOTE

The function was borrowed from here

like image 27
Dan Drews Avatar answered Oct 04 '22 21:10

Dan Drews