0

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

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; }
    }
4

3 回答 3

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例如,会给您一个不合适的值
  • 自然排序
于 2013-07-22T05:34:40.537 回答
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
}
于 2013-07-22T05:38:39.123 回答
0

您可以在您的产品类中实现 ICompareable-Interface。然后该类看起来像: public class product : IComparable { public int productid { 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();
于 2013-07-22T05:44:37.837 回答