简体   繁体   中英

lambda expression to fetch multiple array element with special characters

How to get a list of values which has special characters in it using lambda expression?

I have a list of text-items in an array named values and want the list of text-items containing special characters from it.

var specialCharacters = new string[] { ",", ":", "=" };

I tried couple of times and it didn't worked.

var ans = Array.FindAll(values, value => value.Split(specialCharacters, StringSplitOptions.None).Length > 0);

alternately I was tried

var ans2 = values.Where(value => (value.Split(specialCharacters, StringSplitOptions.None)).Length > 0).ToList();

Both expression didn't worked for me. Output is same as the array "values".

you should use this

 var ans2 = values.Where(value => (value.Split(specialCharacters, StringSplitOptions.None)).Length > 1).ToList();

check the length with 1 . because if special Characters not present in value , then also array will be created with length of 1 having the value at its 0 th index.

While @Viplock's answer is good, I don't think splitting all the strings is the most performant way to go about it. Consider something like this:

char[] specialCharacters = { ',', ':', '=' };
IEnumerable<string> result = values.Where(s => ContainsSpecialCharacter(s, specialCharacters));

...with ContainsSpecialCharacter defined like so:

private static bool HasSpecialCharacter(string s, char[] specialCharacters)
{
    return specialCharacters.Any(specialCharacter => s.Contains(specialCharacter));
}

I also changed SpecialCharacters into an array of char s, but that will work either way.

Caveat : I could be wrong about my performance claim; I haven't actually done any measurements. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM