开发者

ordering generic list by size property

Hi I have had to use interfaces before but ive been told i need to implement icomparable in this instance. see below:

internal class doorItem : IComparable
{
    public int CompareTo(doorItem other)
    {
        // The temperature comparison depends on the comparison of the
        // the underlying Double values. Because the CompareTo method is
        // strongly typed, it is not necessary to test for the correct
        // object type.
        return GetNumber(produc开发者_高级运维tSize).CompareTo(GetNumber(other.productSize));
    }
    public string variations { get; set; }
    public double pricerange { get; set; }
    public string viewDetailsLink { get; set; }
    public string height { get; set; }
    public string width { get; set; }
    public string productSize { get; set; }
    public string productImage { get; set; }
    public int countItemsOnSale { get; set; }
    public string optionFor35Product { get; set; }
    private int GetNumber(string str)
    {
//this method gets the int out of the string
        int length = str.Length;
        string output = String.Empty;
        int test = 0;
        bool err = false;

        for (int i = 0; i <= length; i++)
        {
            try
            {
                test = Convert.ToInt32(str.Substring(i, 1));
            }
            catch
            {
                err = true;
            }

            if (!err)
                output += str.Substring(i, 1);
            else
                break;
        }

        return Convert.ToInt32(output);
    }
}

above is the class i have created, door sizes are returned like this: 4dr, 5dr, 6dr etc.. then the getnumber method gets the int out of the string.

i have a generic list in of my custom class in the main method like this:

List<doorItem> d = new List<doorItem>();

i cant work out how to order this list by door size.... PLEASE HELP


It's easiest to do this using LINQ. Then you don't even need to implement IComparable.

var sortedList = doorList.OrderBy( d => d.GetNumber(d.productSize ).ToList();

And make GetNumber public inside the doorItem class.


I don't know if performance is important, but that method for getting the number is pretty horrible, exceptions should only be used in exceptional circumstances! Suggest something like this

StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
    if (Char.IsNumber(c))
    {
        sb.append(c);
    }
}
return Convert.ToInt32(sb.ToString());

For sorting you can do what stecya has suggested, or you could convert this method to a property and sort directly.

public int Size 
{
    get
    {
         return GetNumber(this.productSize);
    }
}
...
d.OrderBy(x=>x.Size);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜