Alex
Alex

Reputation: 3998

Searching List<string> based on string match

I have the following c# List<string>

var lists = new List<string>
{
    "a", "b", "c", "ee", "ja"
}

I now want to find the index of the last item whose alphanumeric value is less than or equal to d, which in this case would be 2 - which represents "c"

Can anyone suggest how I can do this? It needs to be fast as it will be searching large lists.

Is there also a way to do the same comparison for the closest match to "ef" or any set of multiple characters

EDIT - I know I could write a for loop to do this, but is there any other way to do this? Maybe a built in function.

I know if it was a numeric function I could use Linq.

Upvotes: 0

Views: 180

Answers (2)

Theodor Zoulias
Theodor Zoulias

Reputation: 43996

You'll get great performance by using the BinarySearch method, under the condition that your List is sorted. If it isn't, then don't use this method because you'll get incorrect results.

// List.BinarySearch returns:
// The zero-based index of item in the sorted System.Collections.Generic.List`1,
// if item is found; otherwise, a negative number that is the bitwise complement
// of the index of the next element that is larger than item or, if there is no
// larger element, the bitwise complement of System.Collections.Generic.List`1.Count.
int pos = lists.BinarySearch("d");
int resultPos = pos >= 0 ? pos : ~pos - 1;
Console.WriteLine("Result: " + resultPos);

Upvotes: 1

Sean
Sean

Reputation: 62542

You want FindLastIndex

var index = lists.FindLastIndex(value => value.CompareTo("d") < 0);

NOTE: You have to use CompareTo as < doesn't exist for strings.

Upvotes: 3

Related Questions