[边缘] 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