技术交流QQ群【JAVA,.NET,BigData,AI】:170933152
1.对list中的某两个字段按照升序排序
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>();
//2.先排序再分组
testlist =(List<TestDto>)(from m in testlist orderby m.orderno group m by new {m.nroderno , m.ordernodtl} into mygroup select mygroup);
//3.获取一个list中的某个字段最大的值
(from c in biaoming where c.名称== 条件 select c.ManualID).Max();
//4.按照条件查询,先查询再排序
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>();
//5.LINQ中如何按实体的某个属性去重
问题描述
比如有如下实体集合:
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 IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
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 });
方案二
List<Person> distinctPeople = allPeople
.GroupBy(p => p.PersonId)
.Select(g => g.First())
.ToList();
多属性去重:
List<Person> distinctPeople = 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)));