0

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".

1
  • Can you give the sample inputs? If you can have the expected outputs, and the actual outputs, it will be better :) Commented Jan 27, 2016 at 5:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 chars, but that will work either way.

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

2 Comments

Its just a test code. By the way the suggestion to use array of char is good.
If it's test code, brevity is definitely the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.