在linq中排序方法有:
OrderBy() --对某列升序排序
ThenBy() --某列升序后对另一列后续升序排序
OrderByDescending() --对某列降序排序
ThenByDescending() --某列降序后对另一列后续降序排序
举例:
1.现在对集合AllSubjectList按字段column1升序排序后,再按照column2升序排序
<1. var lvThirdSubList =AllSubjectList.OrderBy(m => m.column1).ToList().OrderBy(m=>m.column2).ToList();
<2. var lvThirdSubList =AllSubjectList.OrderBy(m => m.column1).OrderBy(m=>m.column2).ToList();
如果你的vs装了resharper,第二个写法会提示(但不影响排序效果)
"multiple sequential 'OrderBy' invocation is meaningless. Possible 'ThenBy' means"
译为:多个顺序为基准进行排序的调用是没有意义的。可能“ThenBy”的意思,就是说第二个OrderBy可以改为ThenBy
<3. var lvThirdSubList =AllSubjectList.OrderBy(m => m.column1).ThenBy(m=>m.column2).ToList();
2.现在对集合AllSubjectList按字段column1升序排序后,再按照column2降序排序
<1. var lvThirdSubList =AllSubjectList.OrderBy(m => m.column1).ToList().OrderByDescending(m=>m.column2).ToList();
<2. var lvThirdSubList =AllSubjectList.OrderBy(m => m.column1).OrderByDescending(m=>m.column2).ToList();
同样这里也会提示(但不影响排序效果)
"multiple sequential 'OrderBy' invocation is meaningless. Possible 'ThenByDescending' means"
[错误]<3. var lvThirdSubList =AllSubjectList.OrderBy(m => m.column1).ThenByDescending(m=>m.column2).ToList();
这种写法结果按照column1,column2升序排序,跟1.<1效果一样。ThenByDescending(ThenBy)不能这样用。
ThenBy只能跟在OrderBy后面,ThenByDescending只能跟在OrderByDescending后面。