Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C#
Tip/Trick

Searching method for CSV strings: A different way

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
5 Jul 2012CPOL 9.4K   3   3
A new way of searching from a CSV string.

Introduction

There are many scenarios when you have a comma separated value and you would like to search for a particular value from the string. Normally we do a Split operation and iterate through the array for searching for a particular value. Here is a very easy way of searching for a value without split or iteration.

What is different in CSV string search function?

See below example where search string 33 is not present in the str variable. isExist will be false. if we pass some value that is in the str variable then isExist will be true.

C#
string strSearch ="33";
string str = "1,3,4,56,6,62,86";
str = string.Format(",{0},", str);
bool isExist = str.Contains(string.Format(",{0},", strSearch)); 

I personally follow the Split and iteration operation when my data is not more than 20-30, but this method will give me good performance when I have more data to search for.

Here you can see on line 3 we have appended comma (,) on front and rear. The reason is to search for (,strSearch,) from the given input CSV string.

The code is very simple to understand so I am not going into the depths of the code.  

Hope this code will help you in your projects.

License

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


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralWon't pick up items at the start or end of a row Pin
John Brett5-Jul-12 6:14
John Brett5-Jul-12 6:14 
GeneralRe: Won't pick up items at the start or end of a row Pin
Andreas Kroll6-Jul-12 9:48
Andreas Kroll6-Jul-12 9:48 
GeneralRe: Won't pick up items at the start or end of a row Pin
AmitGajjar8-Jul-12 18:05
professionalAmitGajjar8-Jul-12 18:05 

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.