bradoxbl
bradoxbl

Reputation: 91

Use LiNQ to see if a "value" exists from an array in c#

i have the following

string[] statelookup = ConfigurationManager.AppSettings["WstmStateLookUp"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

with these values

"AL, AR, CT, MD, DE, FL, GA, IA, IL, IN, KY, LA, MA, ME, MI, MN, MO, MS, NC, NH, NJ, NY, OH, PA, RI, SC, TN, VA, VT, WI, WV"

I need to see if any line from a file contains one of the above values. A sample line is this

<FIPS>20170<STATE>AL<WFO>AJK

When I use the following, I only get results for whatever is the first item in the statelookup (in this case, AL).

statelookup.Any(a => currentLine.Contains("<STATE>"+a))

i can move items around (say have OH first and ill get the OH result) but I cant seem to be able to return all the lines form the file that contain ANY of the statelookup values.

I have to use

"<STATE"+a 

because AL, AK, and RI can appear in other lines of the file. this way I only look for this spcific instance.

What am i missing?

Upvotes: 0

Views: 1087

Answers (2)

Felipe
Felipe

Reputation: 11959

As mentioned by @user1304444 in the comments, you are splitting the array incorrectly. I've made a working version of the code here:

https://dotnetfiddle.net/pFO6iV

You will notice that the state AL can be found, since there is no preceding space and it therefore becomes simply "AL" in the string array.

I've removed the spaces using string.Replace() but you can do it in many ways.

string[] statelookup ConfigurationManager
    .AppSettings["WstmStateLookUp"]
    .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 0

Chris
Chris

Reputation: 27599

The problem is that your array does not contain what you think it does... IF you split "AL, AR, CT" on commas then you get {"AL"," AR"," CT"}. As you can see every entry except the first has a leading space which is causing your match to not work.

The three options you have are to either store your string without the spaces, split on ", " or better to strip whitespace using the Trim method after the split before putting them into the array. The last is my preferred because it works if you have double or triple spaces (or more) for some reason.

Something like this would work:

string[] statelookup = ConfigurationManager.AppSettings["WstmStateLookUp"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x=>x.Trim()).ToArray();

Upvotes: 2

Related Questions