0

I was working on something that required me to catch the first char of a string. and return if it starts with S or s.

The pseudocode I considered was:

var foodsWithS = Foods.Where(food => food.Name[0] == 'S' || food.Name[0] == "s").Select(i => i.Name);

Unfortunately, this fails. What would be the best way to do this? Currently I have two lambdas to check for each case of the letter.

3
  • ^ In particular the second answer
    – Sayse
    Mar 28, 2016 at 17:41
  • Your pseudocode was close, but as @Jace's answer points out, StartsWith is the right way to do this (assuming you're using LINQ-to-Objects). Mar 28, 2016 at 17:45
  • true . quite similar ... but good to see it in a LAMBDA expression
    – h4mme7
    Mar 28, 2016 at 17:45

2 Answers 2

4

foods.Where(x => x.StartsWith("S", StringComparison.OrdinalIgnoreCase));

2

If you are using a collection of string objects, You can also use StartsWith;

food.StartsWith("s", StringComparison.OrdinalIgnoreCase);

Not the answer you're looking for? Browse other questions tagged or ask your own question.