Monday, April 18, 2016

Search string as the combinations of words, from the collections / List using ExtentionMethods and LINQ

Normally, User searches the records by typing any word and if that matches any record in the list, it fetches and shows those records in the appropriate records.
But there is another Search. What If User enters more than one word, and let the system to fetch the records that finds any combination of those words from the list (JUST LIKE GOOGLE Search), then we have to do something better than the above approach implemented:

Some Class:
public class Users
{
public int ID {get;set;}
public string Name {get;set;}
public string Username {get;set;}
}


The Normal Approach:

// This is my active list of all users
List<Users> allUsers = UserRepository.GetAll();

// This is my search string
string searchString = "Amit Jain";

// Here is all my users that match any words in the search string
List<string> foundUsers = allUsers.Where(s => s.Username.Contains(searchString)).ToList();


The above method will search for 'Amit Jain' as one word in the records of Users Table.



The Approach with combination of searched strings:

Extension Class:
public static class StringExtension
{
  public static bool ContainsAny(this string str, IEnumerable<string> searchTerms)
  {
    return searchTerms.Any(searchTerm => str.ToLower().Contains(searchTerm.ToLower()));
  
 
  public static bool ContainsAll(this string str, IEnumerable<string> searchTerms)
  {
    return searchTerms.All(searchTerm => str.ToLower().Contains(searchTerm.ToLower()));
  }
}


// Here is all my users that match any words in the search string
List<string> foundUsers = allUsers.Where(s => s.Username.ContainsAny(searchString.Split(' '))).ToList();


Here, it will search for individual two words i.e. Amit and Jain in the list of records...

Happy Coding !!!!





No comments:

Post a Comment