在上一篇中有朋友问实现根据多个列排序的问题,现在把修改过的代码放在这里。经过测试已经实现了目标效果。 实体类:
public class Car { private int weight; public int Weight { get { return weight; } set { weight = value; } } private string type; public string Type { get { return type; } set { type = value; } } }适配器:
public class ComparaCarAdapter : IComparer < Car > { string[] _progNames; List<PropertyInfo> pis = new List<PropertyInfo>(); List<string> sortTypes = new List<string>(); public ComparaCarAdapter(params string[] progNames) { _progNames = progNames; Type t = typeof(Car); foreach (string progName in _progNames) { string[] progNameSplit = progName.Split('|'); string sortType = ""; PropertyInfo pi; if (progNameSplit.Length > 1) { sortType = progNameSplit[0]; pi = t.GetProperty(progNameSplit[1]); } else { pi = t.GetProperty(progName); } pis.Add(pi); sortTypes.Add(sortType); } } IComparer 成员IComparer 成员#region IComparer<Employee> 成员 public int Compare(Car x, Car y) { int resualt = 0; for (int i = 0; i < pis.Count; i++) { string sortType = sortTypes[i]; PropertyInfo pi = pis[i]; object xvalue = pi.GetValue(x, null); object yvalue = pi.GetValue(y, null); if (xvalue is string) { resualt = ((string)xvalue).CompareTo((string)yvalue); } else { if (xvalue is int) { resualt = ((int)xvalue).CompareTo((int)yvalue); } else { throw new NotSupportedException(); } } if (sortType.ToUpper() == "DESC") resualt = resualt * -1; if (resualt != 0) { break; } } return resualt; } #endregion } 测试代码: public string test() { Car c1 = new Car(); c1.Weight = 200; c1.Type = "T"; Car c2 = new Car(); c2.Weight = 500; c2.Type = "b"; Car c3 = new Car(); c3.Weight = 300; c3.Type = "b"; Car c4 = new Car(); c4.Weight = 300; c4.Type = "t"; Car c5 = new Car(); c5.Weight = 200; c5.Type = "d"; Car[] cars = new Car[] { c1, c2, c3, c4, c5 }; Array.Sort(cars,new ComparaCarAdapter("ASC|Weight","Desc|Type")); string resualt = ""; foreach (Car c in cars) { resualt += "|" + c.Weight + "," + c.Type; } return resualt; } 说明: new ComparaCarAdapter("ASC|Weight","Desc|Type"); 参数需要中用“|”隔开,前面的代表排序方式(也可不写,如果不写也不用写分隔符),后面的为属性名称。 也可以将数组定义为ArrayList或List,并使用自带的Sort函数。 谢谢 雨中漫步的太阳的指正。 (转载请注明出处,并留言通知,谢谢。) posted on 2008-01-05 18:14 tianyamoon 阅读( ...) 评论( ...) 编辑 收藏转载于:https://www.cnblogs.com/tianyamoon/archive/2008/01/05/1027209.html