Question

I have a list of arrays. Each array consists of a score and a difficulty. Read in from a text file.

This is how I get the data and order it by the score in descending order.

// load highscores
public void LoadScores()
{
    // loop through each line in the file
    while ((line = file.ReadLine()) != null)
    {
        // seperate the score from the difficulty
        lineData = line.Split(',');

        // add each line to the list
        list.Add(lineData);
    }

    // order the list by descending order
    IOrderedEnumerable<String[]> scoresDesc = list.OrderByDescending(ld => lineData[0]);

}

Is it possible to add the a clause to the IOrderedEnumerable so that it orders by the score in descending order where the difficulty is 1 ?

Was it helpful?

Solution

Assuming the "difficulty" is the second item in the array:

 IEnumerable<String[]> scoresDesc =
     list.OrderByDescending(ld => lineData[0])
         .Where(ld => lineData[1] == 1);

You can sort it afterwards, but Where returns an IEnumerable<T>, not an IOrderedEnumerable<T>, so if you need it to be an IOrderedEnumerable<T> then it's cleaner (and faster) to filter the list first:

 IOrderedEnumerable<String[]> scoresDesc =
     list.Where(ld => lineData[1] == 1)
         .OrderByDescending(ld => lineData[0]);

(this is where var eases some pain, since you aren't bound to the return type)

OTHER TIPS

If you want to filter for those of difficulty 1, you can use the .Where() extension method, if you want to sort by more than one field, you can use the .ThenBy() extension method.

first filter then order:

list.Where(x => x.difficulty == 1).OrderByDescending(ld => lineData[0]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top