2 Mayıs 2013 Perşembe

create special Sorting with c#



public class SortByNumber : Comparer<object>
{

    public override int Compare(object x, object y)
    {

        var xParts = x.GetType().GetProperty("Code").GetValue(x, null).ToString().Split(new[] { '.' });
        var yParts = y.GetType().GetProperty("Code").GetValue(y, null).ToString().Split(new[] { '.' });

        xParts = xParts.Select((c) => { return (c == "" ? "0" : c); }).ToArray();
        yParts = yParts.Select((c) => { return (c == "" ? "0" : c); }).ToArray();

        int index = 0;
        while (true)
        {
            bool xHasValue = xParts.Length > index;
            bool yHasValue = yParts.Length > index;
            if (xHasValue && !yHasValue)
                return 1;   // x bigger
            if (!xHasValue && yHasValue)
                return -1;  // y bigger
            if (!xHasValue && !yHasValue)
                return 0;   // no more values -- same
           
            var xValue = int.Parse(xParts[index]);
            var yValue = int.Parse(yParts[index]);

            if (xValue > yValue)
                return 1;   // x bigger
            if (xValue < yValue)
                return -1;  // y bigger
            index++;
        }
    }

        }

//*******//

     
        public class ctry { public string Code{ get; set; }}
        public void tryTest()
        {
         
            List<ctry> cList = new List<ctry>();

            cList.Add(new ctry() { Code= "1.1" });
            cList.Add(new ctry() { Code = "5" });
            cList.Add(new ctry() { Code = "1.5" });
            cList.Add(new ctry() { Code = "1.2" });
            cList.Add(new ctry() { Code = "1.1.2" });
            cList.Add(new ctry() { Code = "1" });
            cList.Add(new ctry() { Code = "1.1.1" });
            cList.Add(new ctry() { Code = "1.11" });
            cList.Add(new ctry() { Code = "1.4" });
            cList.Add(new ctry() { Code = "6" });


            cList.Sort(new SortComparer ());
         
        }
         

Hiç yorum yok:

Yorum Gönder