自定义排序方式

 

public class Custom_sort: IComparer<string>
{
List<string> _strs;
public Custom_sort(string[] strs)
{
_strs = strs.Distinct().ToList();
}
public int Compare(string x, string y)
{
if (x.Substring(x.Length - 2, 2) == y.Substring(y.Length - 2, 2))
{
return _strs.FindIndex(o => o.Equals(x.Substring(0, 2))) - _strs.FindIndex(o => o.Equals(y.Substring(0, 2)));
}
var defx = 0;
var defy = 0;
var xtrany= int.TryParse(x.Substring(x.Length - 2, 2), out defx);
var ytrany = int.TryParse(y.Substring(y.Length - 2, 2), out defy);
if (!xtrany && !ytrany)
{
return 0;
}
return defx - defy;
}
}

//需要写一个类  实现IComparer该接口的方法

 

 

DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Rows.Add(new object[] { "SP15", });
dt.Rows.Add(new object[] { "SU16", });
dt.Rows.Add(new object[] { "SM16", });
dt.Rows.Add(new object[] { "AC1d", });
dt.Rows.Add(new object[] { "AC15", });
dt.Rows.Add(new object[] { "SM15", });
dt.Rows.Add(new object[] { "SP16", });
dt.Rows.Add(new object[] { "SU15", });
dt.Rows.Add(new object[] { "AC16", });
//dr.Fill(dt);

//调用一个Custom_sort类里的一个方法

//重写IComparer里的方法
var c = dt.AsEnumerable().OrderBy(o => o.Field<string>("Name"),coustOrder).CopyToDataTable();
var b = c;

posted @ 2016-05-30 13:36  Jesh_95  阅读(175)  评论(0编辑  收藏  举报