I have a list of strings.
Given a string, I must find the index in the list of the largest string that is smaller than the given string.
For integers I know how to do it:
int givenInteger = 10;
List<int> myList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int index = myList.IndexOf(myList.Where(x => x < givenInteger).Max()); // 8
int result = myList[index]; // 9
My question is how to implement this for a list of strings.
string givenString = "10";
List<string> myListOfStrings = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" };
int index = myListOfStrings.IndexOf(myListOfStrings.Where(x => x < givenString).Max()); // Error 28 Operator '<' cannot be applied to operands of type 'int' and 'string'
string resultingString = myListOfStrings[index];
CodePudding user response:
Where you would like to do this:
x < givenString
you would actually do this:
x.CompareTo(givenString) < 0
x.CompareTo(y)
will return less than zero if x
is less than y
, zero if x
is equal to y
and greater than zero if x
is greater than y
. It will actually return -1, 0 or 1 but you should not rely on CompareTo
returning any specific value other than zero. Any non-zero value is valid when the values are not equal and it is just the sign that indicates the relative order.
CodePudding user response:
if you want to compare the numerics values you need to convert the value to int with the int.Parse methood.
Now you can compare by the values but if you want to compare the strings values use the CompareTo() function.
string givenString = "10";
List<string> myListOfStrings = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" };
int index = myListOfStrings.IndexOf(myListOfStrings.Where(x => int.Parse(x) < int.Parse(givenString)).Max());
string resultingString = myListOfStrings[index];
CodePudding user response:
First, let's parse givenString
into integer value (int
, long
, BigInteger
):
int givenInt = int.Parse(givenString);
then we can loop over myList
:
int index = -1;
for (int i = 0, max = 0; i < myList.Count; i)
if (int.TryParse(myList[i], out int value) &&
value < givenInteger &&
(index < 0 || value > max)) {
max = int.Parse(myList[i]);
index = i;
}
string maxString = index < 0 ? null : myList[index];