List<Student> students = new List<Student>();
List<Student> sortedStudents = students.OrderBy(s => s.num).ToList();
或者用sort方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<stu> s = new List<stu>();
s.Add(new stu("1", DateTime.Now));
s.Add(new stu("2", DateTime.Today));
s.Add(new stu("3", DateTime.Today.AddDays(1)));
//s=s.OrderBy(b=>b.dt).ToList();
s.Sort(CompareByFromTime);
foreach (var d in s)
{
Console.WriteLine(d.name+" "+d.dt);
}
Console.Read();
}
public static int CompareByFromTime(stu x, stu y)
{
if (x == null)
{
if (y == null)
{
return 0;
}
return 1;
}
if (y == null)
{
return -1;
}
int retval = y.dt.CompareTo(x.dt);
return retval;
}
}
public class stu
{
public string name { get; set; }
public DateTime dt { get; set; }
public stu(string name, DateTime dt)
{
this.name = name;
this.dt = dt;
}
}
}
Dictionary排序
<span style="white-space:pre"> </span> Dictionary<int, string> dd = new Dictionary<int, string>();
dd.Add(1, "111");
dd.Add(3, "333");
dd.Add(2, "222");
dd = dd.OrderBy(d => d.Key).ToDictionary(k => k.Key, v => v.Value);
foreach (var d in dd)
{
Console.WriteLine(d.Key+" "+d.Value);
}
Console.Read();
或者可以这样 var dd1 = from d in dd orderby d.key ascending/descending select d //这样写要新建一个对象 不是很爽