对象数组根据某属性列的灵活排序 (续)
在上一篇中有朋友问实现根据多个列排序的问题,现在把修改过的代码放在这里。经过测试已经实现了目标效果。
实体类:
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; }
}
}
{
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 成员
}
测试代码:{
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
}
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;
}
说明:{
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函数。
谢谢雨中漫步的太阳的指正。
(转载请注明出处,并留言通知,谢谢。)