-2
List<string> list = new List<string>() { " A ", "b" , "C"};

bool status = list.Contains(input);

I get the following status when I checked in console.

Case 1: string input = "A"; // false
Case 2: string input = "B"; // false
Case 3: string input = "C"; // true
Case 4: string input = "c "; // false 
Case 5: string input = " C"; // false
Case 2: string input = "b"; // true

I want everything to be true, hence decided to trim and also convert both to lower. I however, don't know what would be the order, first trim or first convert to lower. Also, I dont know how to do it for list, please help me.

UPDATE

found answer to part of my question. I can do input.ToLower().Trim();

But is it the right order? And how to do the same for list items in this example?

Jasmine
  • 5,186
  • 16
  • 62
  • 114
  • https://stackoverflow.com/questions/3947126/case-insensitive-list-search - use this answer and also add your call to Trim() – Mike Jan 16 '19 at 13:53
  • 3
    You can do `list.Select(s => s.Trim().ToLower()).Contains(input.ToLower())`. – SᴇM Jan 16 '19 at 13:55
  • 1
    Possible duplicate of [LINQ Contains Case Insensitive](https://stackoverflow.com/questions/3360772/linq-contains-case-insensitive) – Linda Lawton - DaImTo Jan 16 '19 at 13:56
  • 1
    The best is not to use `ToLower` at all but the overload with a comparer, pass `StringComparer.InvariantCultureIgnoreCase`. You can google "turkish i problem", it's also more efficient – Tim Schmelter Jan 16 '19 at 13:57
  • @SeM: Thank you so much. May I ask why you didn't trim input? Also, why you have chosen first the trim and then to lower in the select? – Jasmine Jan 16 '19 at 13:58
  • @Learner: why you store them with spaces at all? You can remove them before you add them to the list. – Tim Schmelter Jan 16 '19 at 13:59
  • @Rango Well you can trim input too if you needed. Well it's kind of feels natural to trim first to get your char, then lower it. – SᴇM Jan 16 '19 at 15:20
  • Perhaps if it’s not timed first possible format exception in some case as it tries to convert to lower the empty space and exception, that’s why want to trim first I thought? – Jasmine Jan 16 '19 at 20:28

1 Answers1

-1
list = list.ConvertAll(d => d.ToLower().Trim());

This should help you to convert all the elements in your list to lowercase and trim extra space. This will pass all the conditions where there is a lower case string and no white space. Hope this helps.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215