De-prioritization and sequencing are frequently encountered problems in the development process, and this article summarizes them.
Go heavy
Method 1: Use the built-in distinct
The code is as follows:
Method 1: Use the default distinct method//only for the primitive type list, for custom type combination field conditions require custom equality comparer implementation IEqualityComparer interface, compare trouble var result1 = list. Distinct (). ToList ();
Method 2: Use GroupBy
The code is as follows:
Method 2: Use 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:
Method 3: Use your own extended Distinctby method//Use HashSet key cannot repeat the attribute var result3 = list. Distinctby (p = new {p.bunkcode, p.bunkprice}) . ToList ();
Please refer to the complete code:
<summary>///test Type///</summary>public class Testdistinctclass{public int Id {get; set;} public string Bunkcode {get; set;} Public double Bunkprice {get; set;}} <summary>///test Go heavy//</summary>private static void Testdistinct () {//data source var list = new list< testdistinctclass> {New Testdistinctclass {id= 1, bunkcode= "A", Bunkprice = 101},new Testdistinctclass {id= 2, bunkcode= "B", bunkprice= 102},new Testdisti Nctclass {id= 3, bunkcode= "C", bunkprice= 103},new testdistinctclass { Id= 4, bunkcode= "D", bunkprice= 104},new testdistinctclass {id= 5, Bunkcode= "A", bunkprice= 101}};//Method 1: Use the default distinct method//only for the primitive type list, the custom equality comparer implementation is required for custom type combination field conditions iequality Comparer interface, compare trouble var result1 = list. Distinct (). ToList ();//Method 2: Use Groupbyvar result2 = list. GroupBy (P => New {p.bunkcode, p.bunkprice}). Select (P = = P.first ()). ToList ();///Method 3: Use your own extended Distinctby method//Use the HashSet key cannot repeat the attribute var result3 = list. Distinctby (p = new {p.bunkcode, p.bunkprice}). ToList ();}
At the same time, I also posted the extension method:
<summary>///extension distinct///</summary>///<typeparam name= "TSource" ></typeparam>///< Typeparam name= "TKey" ></typeparam>///<param name= "source" ></param>///<param name= " Keyselector "></param>///<returns></returns>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;}}}
Sort
As for sorting, it's good to use the APIs provided by LINQ, such as: