c# Trying to reverse a list

Viewed 107981

I have the following code:

public class CategoryNavItem
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Icon { get; set; }

    public CategoryNavItem(int CatID, string CatName, string CatIcon)
    {
        ID = CatID;
        Name = CatName;
        Icon = CatIcon;
    }
}

public static List<Lite.CategoryNavItem> getMenuNav(int CatID)
{
    List<Lite.CategoryNavItem> NavItems = new List<Lite.CategoryNavItem>();

    -- Snipped code --

    return NavItems.Reverse();
}

But I get the following error:

Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<Lite.CategoryNavItem>'

Any ideas why this might be?

8 Answers

If you have a list like in your example:

List<Lite.CategoryNavItem> NavItems

You can use the generic Reverse<> extensions method to return a new list without modifiying the original one. Just use the extension method like this:

List<Lite.CategoryNavItem> reversed = NavItems.Reverse<Lite.CategoryNavItem>();

Notes: You need to specify the <> generic tags to explicit use the extension method. Don't forget the

using System.Linq;

I had a situation where none of the suggested options suited me. So, if you:

  • don't want to use someList.Reverse() because it returns nothing (void)
  • don't want to use someList.Reverse() because it modifies source list
  • use someList.AsEnumerable().Reverse() and get the Ambiguous invocation error

You can try Enumerable.Reverse(someList) instead.

Don't forget the:

using System.Linq;
Related