Home > database >  Sort alphabetically categories in list
Sort alphabetically categories in list

Time:09-28

I have a list with items that have category.

enum class ItemCategory {
    ACCOUNT,
    CARD,
    OTHER,
    INVESTMENTS,
    LOAN
}

I sort items alphabetically by category:

items = itemList.sortedBy { it.category.name }.groupBy { it.category }

Output now: ACCOUNT, CARD, INVESTMENTS, LOAN, OTHER, PAYMENT

Expected: ACCOUNT, CARD, INVESTMENTS, LOAN, PAYMENT, OTHER

CodePudding user response:

The Output Now of: ACCOUNT, CARD, INVESTMENTS, LOAN, OTHER, PAYMENT is correct alphabetically.

If you REQUIRE the output to be: ACCOUNT, CARD, INVESTMENTS, LOAN, PAYMENT, OTHER

You can assign numerical values to the Enum values like so:

public enum ItemCategory 
{
    ACCOUNT = 0, 
    CARD = 1, 
    INVESTMENTS = 2, 
    LOAN = 3, 
    PAYMENT = 4,
    OTHER = 5
}

Then when doing the Sorting/Ordering you can do:

var itemList = new List<ItemCategory>
{
    ItemCategory.CARD,
    ItemCategory.ACCOUNT,
    ItemCategory.OTHER,
    ItemCategory.INVESTMENTS,
    ItemCategory.LOAN,
    ItemCategory.PAYMENT
};
        
var sortedList = itemList.OrderBy(i => (int)i).ToList();

Then you can iterate through the list and it will be in the following order:

ACCOUNT
CARD
INVESTMENTS
LOAN
PAYMENT
OTHER
  • Related