-3

I have this List:

List<string> headers = new List<string>(); 
headers.Add("Red"); 
headers.Add("Blue"); 
headers.Add("Green");
headers.Add("Black");

And I have this function:

private int getColorIndex(string colorName , List<string> headers)
{
     int index = LINQ;
}

In getColorIndex function I want to write LINQ that returns the index of specific color from headers list(in colorName variable).

For example if colorName is black the value of index will be 3.

The colorName can contain big or small letters.

For example:

  colorName = Black or colorName = black

Any idea how can I write this LINQ?

Michael
  • 13,950
  • 57
  • 145
  • 288

1 Answers1

3

You don't need LINQ for that. List has an FindIndex method. It takes a predicate and returns the index of the first element that matches. In the predicate you can compare the strings using String.Equals and use a StringComparison parameter to ignore the case.

private int getColorIndex(string colorName , List<string> headers)
{
     int index = headers.FindIndex(s => String.Equals(s, colorName, StringComparison.InvariantCultureIgnoreCase));
}
Domysee
  • 12,718
  • 10
  • 53
  • 84