1、使用Linq的OrderBy进行排序
List<string> a = new List<string> { "b", "c", "a", "aa" }; var b = a.OrderBy(o => o).ToList(); //使用区域敏感排序规则和固定区域比较字符串。 var b = a.OrderBy(o => o, StringComparer.InvariantCulture).ToList(); //使用区域敏感排序规则、固定区域来比较字符串,同时忽略被比较字符串的大小写。 var b = a.OrderBy(o => o, StringComparer.InvariantCultureIgnoreCase).ToList();
2、使用Linq的group by进行分组
示例数据:
ID Counter SrvID FirstName
-- ------ ----- ---------
1 34 66M James
5 34 66M Keith
3 55 45Q Jason
2 45 75W Mike
4 33 77U Will
list1.GroupBy(item => new { Counter = item.Counter, SrvID = item.SrvID })
.Select(group => new {
ID = group.First().ID,
Counter = group.Key.Counter,
SrvID = group.Key.SrvID,
FirstName = group.First().FirstName})
.OrderBy(item => item.ID);
或者
var query =
from record in list1
group record by new {record.Counter, record.SrvID } into g
let winner =
(
from groupedItem in g
order by groupedItem.ID
select groupedItem
).First()
select winner;
或者
var otherQuery = list1
.GroupBy(record => new {record.Counter, record.SrvID })
.Select(g => g.OrderBy(record => record.ID).First());
分组后数据:
ID Counter SrvID FirstName
-- ------ ----- ---------
1 34 66M James
2 45 75W Mike
3 55 45Q Jason
4 33 77U Will
相关文档:.NET(C#) System.Linq中实现多列group by(分组)的示例代码