-1

使用此处的示例/教程如何按零件编号对该列表进行排序?目前该列表只是按照用户添加的顺序打印:

    for(int i = 0; i < Parts.Count; i++)
    {
        CarPart part = Parts.Retrieve(i);
        Console.WriteLine("\nCar Part Information");
        Console.WriteLine("Part #:      {0}", part.PartNumber);
        Console.WriteLine("Description: {0}", part.PartName);
        Console.WriteLine("Unit Price:  {0:C}", part.UnitPrice);
    }
4

2 回答 2

1

如果您需要能够在中间插入和删除很多,您可以考虑使用 SortedDictionary,例如:

(注意:这要求 PartNumber 是唯一的;不同的部分不能有相同的 PartNumber)

using System;
using System.Collections.Generic;

namespace Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var parts = new SortedDictionary<string, CarPart>(); // Key is a string.

            var part = new CarPart{PartNumber = "NumberOne", PartName = "NameOne", UnitPrice = 100.0m};
            parts.Add(part.PartNumber, part);

            part = new CarPart{PartNumber = "NumberTwo", PartName = "NameTwo", UnitPrice = 100.0m};
            parts.Add(part.PartNumber, part);

            part = new CarPart{PartNumber = "NumberThree", PartName = "NameThree", UnitPrice = 100.0m};
            parts.Add(part.PartNumber, part);

            part = new CarPart{PartNumber = "NumberFour", PartName = "NameFour", UnitPrice = 100.0m};
            parts.Add(part.PartNumber, part);

            foreach (var p in parts)
            {
                // Part numbers printed out in *alphabetical* order (because they are strings).

                Console.WriteLine("Part number = " + p.Value.PartNumber);
            }
        }
    }

    public sealed class CarPart
    {
        public string PartNumber;
        public string PartName;
        public Decimal UnitPrice;
    }
}
于 2013-03-24T17:58:58.500 回答
1
foreach(part in Enumerable.Range(0,Parts.Count)
                            .Select(i => Parts.Retrieve(i))
                            .OrderBy(p => p.PartNumber))
{
        Console.WriteLine("Part #:      {0}", part.PartNumber);
}

但如果你ListOfParts能回来就更好了IEnumerable<CarPart>

它可能是这样的

public IEnumerable<int> AllParts
{
    get
    {
        for (Current = Head; Current != null; Current = Current.Next)
        {
            yield return Current;
        }
    }
}

用法是

foreach(part in Parts.AllParts.OrderBy(p => p.PartNumber))
{
    Console.WriteLine("Part #:      {0}", part.PartNumber);
}
于 2013-03-24T17:33:42.577 回答