本文共 3006 字,大约阅读时间需要 10 分钟。
testlist=testlist.OrderBy(s=>new{s.cd1,s.cd2}).ToList<TestDto>();
List<Student> stu = (List<Student>)Session["StudentList"];
下面是详细一点的排序:
Linq表达式:
//按学号降序
List<Student> stuList = (from s instu orderby s.stuNOdescending select s).ToList<Student>();
//按学号升序
List<Student> stuList = (from s instu orderby s.stuNO select s).ToList<Student>();
使用Lambda表达式排序: //按学号降序
单字段:List<Student> stuList= stu.OrderByDescending(s=> s.orderid).ToList<Student>(); 多字段:List<Student> stuList= stu.OrderByDescending(s=> new{s.stuNO,s.stuName}).ToList<Student>(); //按学号升序 单字段:List<Student> stuList= stu.OrderBy(s=> s.stuNO).ToList<Student>(); 多字段:List<Student> stuList= stu.OrderBy(s=> new{s.stuNO,s.stuName}).ToList<Student>(); 多字段主次顺序排序情况,先按no排序,再按name排序 List<Student> stuList= stu.OrderBy(s=> s.stuNO).ThenBy(s=> s.stuName).ToList<Student>(); List<Student> stuList= stu.OrderBy(s=> new{ s.stuNO }).ThenBy(s=> new{s.stuName}).ToList<Student>();testlist =(List<TestDto>)(from m in testlist orderby m.orderno group m by new {m.nroderno , m.ordernodtl} into mygroup select mygroup);
(from c in biaoming where c.名称== 条件 select c.ManualID).Max();
LstTmp = (from m in TmpLst where (m.testcd == "1") && (m.testcd2 == "2") select m).ToList<TestDto>().OrderBy(s => new { s.sor1, s.sort2 }).ToList<TestDto>();
比如有如下实体集合:
Person1: Id=1, Name="Test1"Person2: Id=1, Name="Test1"Person3: Id=2, Name="Test2"
如何使用LINQ按 Person.Id 去重,返回的集合只包含 Person1 和 Person3 ?
创建一个静态扩展类:这个主意一下,这个可以放到一个命名空间下,然后再写一个类:
像下面这样,这样才能用:
static class ListExtendMethod { public static IEnumerableDistinctBy (this IEnumerable source, Func keySelector) { HashSet seenKeys = new HashSet (); foreach (TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } }
public static IEnumerableDistinctBy (this IEnumerable source, Func keySelector){ HashSet seenKeys = new HashSet (); foreach (TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } }}
调用方法:
var query = people.DistinctBy(p => p.Id);
如果需要按多个属性去重,则可以使用匿名对象,如:
var query = people.DistinctBy(p => new { p.Id, p.Name });
ListdistinctPeople = allPeople .GroupBy(p => p.PersonId) .Select(g => g.First()) .ToList();
多属性去重:
ListdistinctPeople = allPeople .GroupBy(p => new {p.PersonId, p.FavoriteColor} ) .Select(g => g.First()) .ToList();
var uniquePeople = from p in people group p by new {p.ID} //or group by new {p.ID, p.Name, p.Whatever} into mygroup select mygroup.FirstOrDefault();
Persons.ToLookup(p => p.Id).Select(coll => coll.First());
var result = people.Where(p => !people.Any(q => (p != q && p.Id == q.Id)));
转载地址:http://fltdf.baihongyu.com/