Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a list alphabetically in a console-app?

I am able to manually enter items and then store them into a list. When I do that and then press "2" to view items (which loads the list), they don’t sort alphabetically. I’ve tried a lot of code but nothing has changed.

I am trying to sort alphabetically by name. The way I input data is: name first, then description, then Id. I’ve tried a CompareTo method with currentItemList.Sort() with no results.

private static List<string> ProductTypeList;
private static Dictionary<string, List<Item>> Products;

public class Item: IComparable<Item>
        {
            public string ProductType;
            public string Name;
            public string Description;
            public int Id;

            public Item(string productType, string name, string description, int id)
            {
                ProductType = productType;
                Name = name;
                Description = description;
                Id = id;

                List<Item> itemList;
                if (Products.ContainsKey(productType))
                {
                    itemList = Products[productType];
                }
                else
                {
                    ProductTypeList.Add(productType);
                    itemList = new List<Item>();
                    Products.Add(productType, itemList);
                }
                itemList.Add(this);
            }
            public int CompareTo(Item b)
            {
                // Alphabetic sort name[A to Z]
                return this.Name.CompareTo(b.Name);
            }
         }

I have more code (that just displays the current default list I’ve already created beforehand, and then my menu with switch/case).
This snippet of code below (in my switch case) is where I believe I should be trying to sort the items, before they display.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

case 1: // View Products
Console.Clear();
foreach (var item in currentItemList) <-- error comes from this line
    {
    currentItemList.Sort(); // <--- sort alphabetically, compareTo()
    item.Display();
    }
    break;

I have tried using more variations, but with list.Sort() I get a compare error.

List<Tool> SortedList = currentToolList.OrderBy(o => o.Name).ToList();
Also LINQ with currentToolList.Sort();

I get this error: "Unhandled exception. System.InvalidOperationException: Collection was modified; enumeration operation may not execute." on this line:

>Solution :

It seems that you should first sort the list and then loop over it:

// Sorted representation
var sorted = currentItemList.OrderBy(item => item.Name);

// Time to loop over sorted and Display the items
foreach (var item in sorted)
  item.Display();

Very same idea if you want to sort in place:

// First sort
currentItemList.Sort((left, right) => 
   StringComparer.Ordinal.Compare(left?.Name, right?.Name));

// Then Display:
foreach (var item in currentItemList)
  item.Display();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading