Custom logic while filtering. (Comparing strings)

List can be filtered using various methods like Linq Where or using List.Contains method but there are situations where you need some custom logic while filtering.

Mostly while filtering List, you can simply use Linq Where or string.Contains method, e.g., if you have a string "My name is Khan" and you want to compare that with “My name” or “is Khan” so string.Contains would be the simplest way to go through but what if you require to compare each word regardless of their sequence like if you have to compare “My name is Khan” with “Khan name” in this case string.Contains would return false.

public static bool StringLike(string strMain, string strSub)
{
    string[] subStrings = strSub.Split(' ');

    foreach (string subString in subStrings)
    {
        if (strMain.Contains(subString) == false)
        {
            return false;
        }
    }
    return true;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s