How to ignore -ve value while sorting generic list in c#.
-
Hi all, I want to ignore negative while sorting a generic array list. eg. If list contain following values 0.3 0.2 -0.3 after sofrting it should values should be in following order 0.3 -0.3 0.2 Any solution guyz. Thanks in advance.
People Laugh on me Because i am Different but i Laugh on them Because they all are same.
-
Hi all, I want to ignore negative while sorting a generic array list. eg. If list contain following values 0.3 0.2 -0.3 after sofrting it should values should be in following order 0.3 -0.3 0.2 Any solution guyz. Thanks in advance.
People Laugh on me Because i am Different but i Laugh on them Because they all are same.
Write a class that implements
IComparer
.public class myComparer : IComparer
{
public Boolean Descending;
#region IComparer Memberspublic int Compare(object x, object y) { Double obj1 = (Double)x; if (obj1 < 0) obj1 = -(obj1); Double obj2 = (Double)y; if (obj2 < 0) obj2 = -(obj2); if (Descending ) { if (obj1 < obj2 ) return 1; if (obj1 > obj2) return -1; } else { if (obj1 > obj2 ) return 1; if (obj1< obj2) return -1; } return 0; } #endregion
}
Pass a object of your custom class in
ArrayList.sort
methodArrayList arr = new ArrayList();
arr.Add(0.3);
arr.Add(0.2);
arr.Add(-0.3);myComparer objComparer = new myComparer();
objComparer.Descending = true;
arr.Sort(objComparer);modified on Monday, August 30, 2010 5:31 AM
-
Hi all, I want to ignore negative while sorting a generic array list. eg. If list contain following values 0.3 0.2 -0.3 after sofrting it should values should be in following order 0.3 -0.3 0.2 Any solution guyz. Thanks in advance.
People Laugh on me Because i am Different but i Laugh on them Because they all are same.
you can do some thing like this
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<decimal> lstIntCol = new List<decimal>();
lstIntCol.Add(0.3M);
lstIntCol.Add(0.2M);
lstIntCol.Add(-0.3M);
lstIntCol.Sort(new decimalComparer());
foreach (decimal d in lstIntCol)
{
Response.Write(d.ToString() + "--");
}
}
}public class decimalComparer : System.Collections.Generic.IComparer<decimal>
{#region IComparer<decimal> Members public int Compare(decimal x, decimal y) { return decimal.Compare(Math.Abs(y),Math.Abs(x)); } #endregion
}