您的位置:首页 > 其它

List<T>.Sort() 排序的用法

2016-07-07 17:31 411 查看
List<T> 可以通过 .Sort()进行排序,但是当 T 对象为自定义类型时(比如自定义模型),就需要 IComparable接口重写其中的方法来实现,实现代码如下:

class Program
{
static Func<Model, int> where = a => a.id;
static Func<Model, bool> wherelambda = a => a.id < 3;
static void Main(string[] a)
{
List<Model> result = GetData().ToList();
result.Sort();          //排序
}

/// <summary>
/// 拼装数据
/// </summary>
/// <returns></returns>
#region
public static IList<Model> GetData()
{
IList<Model> list = new List<Model>();
for (int i = 0; i <= 10; i++)
{
Model model = new Model();
model.id = i;
model.Name = "名字" + i;
model.Email = string.Format("12345@QQ{0}.com.cn", i);
list.Add(model);
}
return list;
}
#endregion
}

/// <summary>
/// 自定义模型 一定要继承 IComparable<T>接口
/// </summary>
public class Model : IComparable<Model>
{
public int id { get; set; }

private int Sex { get; set; }

public string Name { get; set; }

public DateTime? BirthDate { get; set; }

public string Email { get; set; }

public string Phone { get; set; }

public int CompareTo(Model model)
{
if (model.id == id && model.Name.Equals(Name))
return 0;
else
{
if (id > model.id)
{
return -1;
}
if (Name.CompareTo(model.Name) > 0)
{
return -1;
}
else
return 1;
}

}
}


如果不继续IComparable接口,也可以直接在 .Sort()方法里面写,代码如下:

class Program
{
static Func<Model, int> where = a => a.id;
static Func<Model, bool> wherelambda = a => a.id < 3;
static void Main(string[] a)
{
List<Model> result = GetData().ToList();
result.Sort((a,b)=>{
if (b.id == a.id && b.Name.Equals(a.Name))
return 0;
else
{
if (a.id > b.id)
{
return -1;
}
if (a.Name.CompareTo(b.Name) > 0)
{
return -1;
}
else
return 1;
}
});          //排序
}


按照功能排序:List<T> < IList<T> < ICollection<T> < IEnumerable<T>

按照性能排序:IEnumerable<T> < ICollection<T> < IList<T> < List<T>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: