Forum Xamarin.Forms

Help Sorting CollectionView

ap4321ap4321 Member ✭✭

Im tinkering with XAML C# for the first time, playing with some existing data. I need to sort by CollectionView and im getting abit lost.

I want to sort on the HighScores page by Score



Answers

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    That code belongs in your ViewModel, which is conveniently the only file you neglected to post. Also, please post your code as text, not screenshots, in the future.

  • ap4321ap4321 Member ✭✭

    Thanks Sorry, and noted. ViewModel attached.

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    So LINQ has a pretty convenient OrderByDescending method, which I would just drop into your loading command:

    Items.Clear();
    var items = await DataStore.GetItemsAsync(true);
    var sortedItems = items.OrderByDescending(i => i.Score);
    foreach (var item in sortedItems)
    {
        Items.Add(item);
    }
    
  • ap4321ap4321 Member ✭✭

    Thanks, that didnt seem to work for sorting Score, but if I was to sort by name that did. Is that due to Score being a string not an int?
    I cant change score to an int as that causes more problems.
    Is there a way of sorting strings which are numbers?

  • JoeMankeJoeManke USMember ✭✭✭✭✭
    edited February 20

    I'm concerned about what type of problems Score being an int would cause you.

    You could create an implementation of IComparer that parses Score into a number for sorting purposes. This documentation has an example.

  • LandLuLandLu Member, Xamarin Team Xamurai

    We could parse it to double like:

    var sortedItems = items.OrderBy(i => double.Parse(i.Score)).ToList();
    

    If all the score are valid double strings.

Sign In or Register to comment.