c#如何从列表中排序大小

时间:2013-07-22 05:28:50

标签: c# asp.net

我想展示我的产品尺寸从小到大?:

M,XL,S必须导致:S,M,XL

C#

 protected void Page_Load(object sender, EventArgs e)
        {
            List<product> list = new List<product>();
            product p1 = new product() {productid=1,Size="M" };
            product p2 = new product() { productid = 2, Size = "XL" };
            product p3 = new product() { productid = 3, Size = "S" };
            list.Add(p1);
            list.Add(p2);
            list.Add(p3);
            List<product> orderlist = list.OrderBy(o => o.Size).ToList();

            //list.Sort(size);
            foreach (var pr in orderlist)
            {
                Response.Write(pr.Size +"<br/>");
            }
        }



   public class product
    {
        public int productid{ get; set; }
        public string Size { get; set; }
    }

3 个答案:

答案 0 :(得分:10)

最简单的方法可能是以正确的顺序将Size更改为枚举:

public enum ClothingSize
{
    [Abbreviation("S")]
    Small = 0,
    [Abbreviation("M")]
    Medium = 1,
    [Abbreviation("L")]
    Large = 2,
    [Abbreviation("XL")]
    ExtraLarge = 3
}

(有各种方法将枚举映射到缩写文本形式 - 我给出了一个你自己声明的AbbreviationAttribute的例子;你可以使用现有的DescriptionAttribute,但描述比标识符本身更简洁,这有点奇怪。)

使用枚举的好处:

  • 错别字的风险
  • 更容易验证给定大小实际上是否有效(尽管您需要进行验证 - 枚举只是命名数字; (ClothingSize) 15会给您一个不合适的值,例如
  • 自然排序

答案 1 :(得分:1)

一个好的方法是在product类型上实现IComparable,如下所示:

public class product : IComparable
{
     // YOUR CODE
#region IComparable<Employee> Members

     public int CompareTo( product other )
     {
         // Comparison logic
         // return 1 if other size is greater
         // -1 if other size is smaller
         // 0 if both sizes are equal
     }

#endregion
}

答案 2 :(得分:0)

您可以在产品类中实现ICompareable-Interface。然后该课程如下:   公共类产品:IComparable     {         public int productid {get;组; }         public string Size {get;组; }

    /// <summary>
    /// do compare-stuff like if-statement on the size or something else
    /// </summary>
    /// <param name="compareProduct">the product to compare with this</param>
    /// <returns>
    /// 0  if both product-sizes are equal
    /// 1  if compareProduct.Size is larger
    /// -1 if this.Size is larger
    /// </returns>
    public int CompareTo(product compareProduct)
    {
        // TODO: implement
    }
}

然后您只需致电:

即可对列表进行排序
list.Sort();