c# Trying to reverse a list

102,871

Solution 1

Try:

NavItems.Reverse();
return NavItems;

List<T>.Reverse() is an in-place reverse; it doesn't return a new list.

This does contrast to LINQ, where Reverse() returns the reversed sequence, but when there is a suitable non-extension method it is always selected in preference to an extension method. Plus, in the LINQ case it would have to be:

return someSequence.Reverse().ToList();

Solution 2

One workaround would be Return NavItems.AsEnumerable().Reverse();

Solution 3

.Reverse() on a list reverses the items within the list, it does not return a new reversed list.

Solution 4

Reverse() does not returns reversed list itself, it modifies original list. So rewrite it as following:

return NavItems.Reverse(); 

TO

NavItems.Reverse(); 
return NavItems;

Solution 5

Reverse() does not return a List as expected of your function.

NavItems.Reverse();
return NavItems;
Share:
102,871
Tom Gullen
Author by

Tom Gullen

Me Web developer. Website http://www.scirra.com

Updated on October 18, 2021

Comments

  • Tom Gullen
    Tom Gullen over 2 years

    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?