Click here to Skip to main content
14,599,948 members

C# - Wildcard Search Using LINQ

Rate this:
4.56 (4 votes)
Please Sign up or sign in to vote.
4.56 (4 votes)
10 Aug 2013CPOL
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#, Javascript/Node.js, Various flavors of databases, and anything else I find interesting. I am always looking for new information, and value your feedback (especially where I got something wrong!)

Comments and Discussions

 
QuestionFor Search Pin
ashuslove26-Jun-14 2:42
Memberashuslove26-Jun-14 2:42 
Questioncan you please add project , it's not working in my project. thanks Pin
SAQIB ASLAM GANATRA8-Jun-14 22:04
MemberSAQIB ASLAM GANATRA8-Jun-14 22:04 
Questionhelp Pin
Jony Perveg13-Jan-14 7:00
MemberJony Perveg13-Jan-14 7:00 
AnswerRe: help Pin
John Atten13-Jan-14 12:39
MemberJohn Atten13-Jan-14 12:39 
QuestionUse Regex Pin
darrellp27-Aug-13 20:01
Memberdarrellp27-Aug-13 20:01 
Just wanted to point out that you can do this and much more by just using something like
list.Where(s=>rgx.Match(s).Success)
where rgx is a Regex object.
AnswerRe: Use Regex Pin
John Atten28-Aug-13 1:24
MemberJohn Atten28-Aug-13 1:24 
QuestionThanks. Pin
George Swan10-Aug-13 7:36
MemberGeorge Swan10-Aug-13 7:36 
AnswerRe: Thanks. Pin
John Atten10-Aug-13 7:56
MemberJohn Atten10-Aug-13 7:56 
AnswerRe: Thanks. Pin
John Atten10-Aug-13 8:01
MemberJohn Atten10-Aug-13 8:01 
QuestionLINQ Methods?? Pin
TnTinMn9-Aug-13 13:59
MemberTnTinMn9-Aug-13 13:59 
AnswerRe: LINQ Methods?? Pin
John Atten9-Aug-13 15:49
MemberJohn Atten9-Aug-13 15:49 

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

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

Technical Blog
Posted 8 Aug 2013

Tagged as

Stats

47.8K views
14 bookmarked