[邊緣] C# 專家問遺下

作者: nh60211as   2021-03-22 23:46:13
要依照 Tuple< string, ulong > 的 ulong 排序 List< Tuple< string, ulong > >
有蛇摸簡潔又可以重複利用 Comparer 的寫法ㄇ
目前寫成這樣
private static int CompareTupleSecondValue<T, V>(Tuple<T, V> v1, Tuple<T, V> v2)
{
return Comparer<V>.Default.Compare(v1.Item2, v2.Item2);
}
private static ulong GetMedian<T>(List<Tuple<T, ulong>> list)
{
list.Sort(CompareTupleSecondValue);
if (list.Count == 0)
return 0;
if (list.Count == 1)
return list[0].Item2;
if (list.Count % 2 == 1)
return list[list.Count / 2].Item2;
else
return (list[list.Count / 2 - 1].Item2
+ list[list.Count / 2].Item2) / 2;
}
作者: Apache (阿帕契)   2021-03-22 23:50:00
inline lambda
作者: ZooseWu (N5)   2021-03-22 23:57:00
Comparer是什麼
作者: nh60211as   2021-03-22 23:58:00
System.Collections.Generic內建的,拿來比較兩個值
作者: why8ther (外八喵)   2021-03-23 00:00:00
lambda宣告一次就到處用啊
作者: Apache (阿帕契)   2021-03-23 00:06:00
不然你把Tuple封裝成新物件 內建你的comparator
作者: nh60211as   2021-03-23 00:10:00
也是==,我原本只是想快速寫一個自訂比較的,看來沒這麼方便
作者: ZooseWu (N5)   2021-03-23 00:23:00
我看不懂 我好爛如果要到處用感覺Apache講得方法最好吧 包起來到處用

Links booklink

Contact Us: admin [ a t ] ucptt.com