Reputation: 13
I'm trying to sort my list using an algorithm. The list contains string arrays which holds date, titel and entry.
So the error message I am getting is this:
Error CS0019 Operator '>' cannot be applied to operands of type 'string[]' and 'string[]'
I will not include all of my code, as it is not in English anyway.
List<string[]> loggBok = new List<string[]>();
void nyttInlägg(string datum, string titel, string text) // När användaren anropar denna metoden från menyn, så kommer hans input
// läggas in i vektorn.
{
string[] anteckingar = new string[3] { "", "", "" };
anteckingar[0] = datum;
anteckingar[1] = titel;
anteckingar[2] = text;
loggBok.Add(anteckingar);
bool isSorted = false;
while (!isSorted)
{
isSorted = true;
for (int i = 0; i < loggBok.Count - 1; i++)
{
if ((loggBok[i]) > loggBok[i + 1])
{
string[] temp = loggBok[i + 1];
loggBok[i + 1] = loggBok[i];
loggBok[i] = temp;
}
i = i + 2;
}
}
So basically, every 3 element in the list will hold a stringarray with a date. This is the date that I want to organize. I believe I understand the logic behind the algorithm but I just cannot get the syntax right. I have checked other threads, some with similar problems but none that was 100%. As this is a school project it has to be an algorithm, thus I don't want to make it "easier" or more effective in anyway. Any ideas on how to overcome this horrible error message?
Upvotes: 1
Views: 82
Reputation: 349956
Some issues:
if ((loggBok[i]) > loggBok[i + 1])
lacks a closing parenthesis
The above attempts to compare arrays, while you just want to compare the dates. So you need to reference the date-entry in loggBok[i]
:
if ((loggBok[i][0]) > loggBok[i + 1][0]))
The i
index refers to arrays (triplets), so you should not increase it with three, but just with one, as it will go to the next triplet when you do i++
, which is what you want. So remove i = i + 2
, otherwise you skip some of these triplets.
Upvotes: 1
Reputation: 2851
The operator >
greater than cannot be applied to type array or type string ( as mentioned in other answer comment) - have a look at the documentation here
Each element in the list is an array of strings - with structure:
So the following command will fails if ((loggBok[i]) > loggBok[i + 1]))
as you comparing two arrays with the operator >
.
To retrieve the data you will have loggBok[i][0]
which is a string.
You need to convert them to the correct type(eg. int) in order to use the comparison operator >
.
I assumed the data is a type int -
if (int.TryParse(loggBok[i][0], out int currentElement) &&
int.TryParse(loggBok[i + 1][0], out int nextElement) &&
currentElement > nextElement)
{
string[] temp = loggBok[i + 1];
loggBok[i + 1] = loggBok[i];
loggBok[i] = temp;
}
You can read about the TryParse here
Upvotes: 0