Home > Article > Backend Development > How to remove duplicates and sort
Deduplication and sorting are problems often encountered during the development process. This article will summarize them.
Method 1: Use the built-in distinct
The code is as follows:
//方法1:使用默认的distinct方法//只能针对基元类型列表,对于自定义类型组合字段条件需要自定义相等比较器实现IEqualityComparer接口,比较麻烦var result1 = list.Distinct().ToList();
Method 2: Use GroupBy
The code is as follows:
//方法2:使用GroupByvar result2 = list.GroupBy(p => new { p.BunkCode, p.BunkPrice }) .Select(p => p.First()) .ToList();
Method 3: Use your own extended DistinctBy method
The code is as follows:
//方法3:使用自己扩展的DistinctBy方法//利用HashSet的key不能重复的特性var result3 = list.DistinctBy(p => new { p.BunkCode, p.BunkPrice }) .ToList();
Please refer to the complete code:
/// <summary>/// 测试类型/// </summary>public class TestDistinctClass {public int Id { get; set; }public string BunkCode { get; set; }public double BunkPrice { get; set; } }/// <summary>/// 测试去重/// </summary>private static void TestDistinct() {//数据源var list = new List<testdistinctclass> {new TestDistinctClass { Id= 1, BunkCode= "A", BunkPrice= 101},new TestDistinctClass { Id= 2, BunkCode= "B", BunkPrice= 102},new TestDistinctClass { Id= 3, BunkCode= "C", BunkPrice= 103},new TestDistinctClass { Id= 4, BunkCode= "D", BunkPrice= 104},new TestDistinctClass { Id= 5, BunkCode= "A", BunkPrice= 101} };//方法1:使用默认的distinct方法//只能针对基元类型列表,对于自定义类型组合字段条件需要自定义相等比较器实现IEqualityComparer接口,比较麻烦var result1 = list.Distinct().ToList();//方法2:使用GroupByvar result2 = list.GroupBy(p => new { p.BunkCode, p.BunkPrice }) .Select(p => p.First()) .ToList();//方法3:使用自己扩展的DistinctBy方法//利用HashSet的key不能重复的特性var result3 = list.DistinctBy(p => new { p.BunkCode, p.BunkPrice }) .ToList(); }</testdistinctclass>
At the same time, I also posted the extension method:
/// <summary>/// 扩展distinct/// </summary>/// <typeparam></typeparam>/// <typeparam></typeparam>/// <param>/// <param>/// <returns></returns>public static IEnumerable<tsource> DistinctBy<tsource>(this IEnumerable<tsource> source, Func<tsource> keySelector) { HashSet<tkey> seenKeys = new HashSet<tkey>();foreach (TSource element in source) {if (seenKeys.Add(keySelector(element))) {yield return element; } } }</tkey></tkey></tsource></tsource></tsource></tsource>
As for sorting, use the api provided by Linq. Okay, as shown below:
The above is the detailed content of How to remove duplicates and sort. For more information, please follow other related articles on the PHP Chinese website!