我可以手动输入项目,然后将它们存储到列表中。当我这样做然后按“2”查看项目(加载列表)时,它们不会按字母顺序排序。我尝试了很多代码,但没有任何改变。
我正在尝试按名称的字母顺序排序。我输入数据的方式是:先是名称,然后是描述,然后是Id。我已经尝试使用 currentItemList.Sort() 的 CompareTo 方法但没有结果。
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);
}
}
我有更多代码(只显示我事先创建的当前默认列表,然后是带有开关/大小写的菜单)。 下面的这段代码(在我的开关盒中)是我认为我应该在显示之前尝试对项目进行排序的地方。
case 1: // View Products
Console.Clear();
foreach (var item in currentItemList) <-- error comes from this line
{
currentItemList.Sort(); // <--- sort alphabetically, compareTo()
item.Display();
}
break;
我尝试使用更多变体,但是使用 list.Sort() 我得到一个比较错误。
List<Tool> SortedList = currentToolList.OrderBy(o => o.Name).ToList();
Also LINQ with currentToolList.Sort();
我收到此错误:“未处理的异常。System.InvalidOperationException:集合已修改;枚举操作可能无法执行。”在这条线上:
看来你应该first对列表进行排序,然后loop over它:
// 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();
如果你想就地排序,完全相同的想法:
// First sort
currentItemList.Sort((left, right) =>
StringComparer.Ordinal.Compare(left?.Name, right?.Name));
// Then Display:
foreach (var item in currentItemList)
item.Display();
您的 Sort() 方法会改变您当前正在迭代的集合的状态,这是不允许的。
所以你需要在迭代之前对集合进行排序。
在 foreach 块之外进行排序,你应该没问题:
currentItemList.Sort();
foreach (var item in currentItemList) <-- error comes from this line
{
item.Display();
}
break;
你应该像下面这样在“foreach”语句中订购项目:
foreach (var tool in currentToolList.OrderBy(x => x.Name)) //sort here
{
tool.Display();
}