Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

C# - Wildcard Search Using LINQ

, 10 Aug 2013
Rate this:
Please Sign up or sign in to vote.
Wildcard search using LINQ

Introduction

telescope-by-salendron-320

Do you need to create a wild-card style search method using LINQ? It is ridiculously easy.

Below is a simple example, using LINQs with the .StartsWith method defined on the string class. In an application for work, I needed a "Google-like" search performed on a list where with each keystroke, the list is filtered to more closely match what is typed into the search input box.

At work, I am stuck still using Windows Forms, so what you see below is used to populate the venerable Winforms Treeview. The filtering piece, though, can be useful in other situations.

Image by salendron | Some rights reserved

I'm stepping away briefly from my examination of routing in ASP.NET MVC and ASP.NET Web API to toss this little gem out there. There's nothing fancy or new here, but if you are new to LINQ, or just never had to use LINQ with a wildcard search scenario before, this might be helpful.

Basic LINQ Query Using the .StartsWith Method

The wildcard search below will filter the IEnumerable<Company> on the Company.CompanyName property, as well as on the Company.CompanyCode property (which represents the company instance's US Tax ID number).

Basic Code for the Wildcard Search Using LINQ .StartsWith Method
public void LoadListView(IEnumerable<Company> companies, string searchString = "")
{
    IEnumerable<Company> query;
    if (!(searchString.Length > 1))
    {
        query = companies;
    }
    else
    {
        query =
        (from company in companies
         where company.CompanyName.StartsWith(searchString, 
            StringComparison.OrdinalIgnoreCase) 
        || company.CompanyCode.StartsWith(searchString, 
            StringComparison.OrdinalIgnoreCase)
         orderby company.CompanyName
         select company);
    }

    foreach (var filteredCompany in query)
    {
        // Load the ListView control . . .
    }
}

In the above code, a source Enumerable is passed in and becomes the target for the filter. Additionally, an optional search string is passed, with an empty string as default. The way the method above is set up, if the search string is not at least one character in length, the entire contents of the source Enumerable are shown. Once the length of the input string is greater than a single character, the filter is applied.

The Search Function Before Typing in the Search Textbox

search-companies-before-typing

As you can see, once we begin to type, and the input string (in this case, "al" so far) length exceeds a single character, the filtering begins:

The Search Function After Typing in the Search Textbox

search-companies-after-typing

Depending upon your needs, you might modify this to display nothing until an input string is present. Also, depending upon the size of your original data set, you might need to apply other strategies to winnow down the starting instance of IEnumerable passed in (in my case, the entire list of companies is supplied. We may have to look at that if it grows too large).

For Case-Insensitivity Use StringComparison.OrdinalIgnoreCase

By default, LINQ will perform a case-sensitive comparison. Not especially useful in this context. To tell LINQ to ignore case, I have provided a second parameter to the StartsWith method, StringComparison.OrdinalIgnoreCase.

LINQ can also utilize the corresponding string methods EndsWith and Contains, which perform their respective functions in the manner implied by their names.

Additional Items of Interest

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

John Atten
Software Developer XIV Solutions
United States United States
My name is John Atten, and my username on many of my online accounts is xivSolutions. I am Fascinated by all things technology and software development. I work mostly with C#, Java, SQL Server 2012, learning ASP.NET MVC, html 5/CSS/Javascript. I am always looking for new information, and value your feedback (especially where I got something wrong!)
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionFor Search Pinmemberashuslove26-Jun-14 2:42 
Questioncan you please add project , it's not working in my project. thanks PinmemberSAQIB ASLAM GANATRA8-Jun-14 22:04 
Questionhelp PinmemberJony Perveg13-Jan-14 7:00 
AnswerRe: help PinmemberJohn Atten13-Jan-14 12:39 
QuestionUse Regex Pinmemberdarrellp27-Aug-13 20:01 
AnswerRe: Use Regex PinmemberJohn Atten28-Aug-13 1:24 
QuestionThanks. PinmemberGeorge Swan10-Aug-13 7:36 
AnswerRe: Thanks. PinmemberJohn Atten10-Aug-13 7:56 
AnswerRe: Thanks. PinmemberJohn Atten10-Aug-13 8:01 
QuestionLINQ Methods?? PinmemberTnTinMn9-Aug-13 13:59 
AnswerRe: LINQ Methods?? PinmemberJohn Atten9-Aug-13 15:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 10 Aug 2013
Article Copyright 2013 by John Atten
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid