List <t>扩展方法First,Second,Third .... Nth

时间:2016-07-04 22:04:19

标签: c# extension-methods

我想访问列表中的第一个,第二个,第三个元素。我可以使用内置的Dictionary<int, Tuple<int, int>> pList = new Dictionary<int, Tuple<int, int>>(); var categoryGroups = pList.Values.GroupBy(t => t.Item1); var highestCount = categoryGroups .OrderByDescending(g => g.Count()) .Select(g => new { Category = g.Key, Count = g.Count() }) .First(); var 2ndHighestCount = categoryGroups .OrderByDescending(g => g.Count()) .Select(g => new { Category = g.Key, Count = g.Count() }) .GetNth(1); var 3rdHighestCount = categoryGroups .OrderByDescending(g => g.Count()) .Select(g => new { Category = g.Key, Count = g.Count() }) .GetNth(2); twObjClus.WriteLine("--------------------Cluster Label------------------"); twObjClus.WriteLine("\n"); twObjClus.WriteLine("Category:{0} Count:{1}", highestCount.Category, highestCount.Count); twObjClus.WriteLine("\n"); twObjClus.WriteLine("Category:{0} Count:{1}", 2ndHighestCount.Category, 2ndHighestCount.Count); // Error here i.e. "Can't use 2ndHighestCount.Category here" twObjClus.WriteLine("\n"); twObjClus.WriteLine("Category:{0} Count:{1}", 3rdHighestCount.Category, 3rdHighestCount.Count); // Error here i.e. "Can't use 3rdHighestCount.Category here" twObjClus.WriteLine("\n"); 方法来访问第一个元素。

我的代码如下:

GetNth()

我已将扩展方法public static IEnumerable<T> GetNth<T>(this IEnumerable<T> list, int n) { if (n < 0) throw new ArgumentOutOfRangeException("n"); if (n > 0){ int c = 0; foreach (var e in list){ if (c % n == 0) yield return e; c++; } } } 编写为:

.Second()
  • 我可以将扩展方法编写为.Third().First()类似于 内置方法 public override init(){ super.init() } public init(annotations: [MKAnnotation]){ super.init() addAnnotations(annotations: annotations) } public func setAnnotations(annotations:[MKAnnotation]){ tree = nil addAnnotations(annotations: annotations) } public func addAnnotations(annotations:[MKAnnotation]){ if tree == nil { tree = AKQuadTree() } lock.lock() for annotation in annotations { // The warning occurs at this line tree!.insertAnnotation(annotation: annotation) } lock.unlock() } 以访问第二和第三个索引?

2 个答案:

答案 0 :(得分:1)

如果您要查找的是单个对象,则不需要自己编写,因为a built-in method已存在。

foo.ElementAt(1)

将为您提供第二个元素等。它与First的工作方式类似,并返回单个对象。

你的GetNth方法似乎正在返回每个第N个元素,而不仅仅是索引N处的元素。我假设这不是你想要的,因为你说你想要类似的东西First

答案 1 :(得分:0)

由于@Eser放弃了并且不想发布正确的方式作为答案,这里有:

你应该做一次转换,将结果收集到一个数组中,然后从中获取三个元素。你现在正在做的方式导致代码重复以及分组和排序多次完成,这是低效的。

var highestCounts = pList.Values
                    .GroupBy(t => t.Item1)
                    .OrderByDescending(g => g.Count())  
                    .Select(g => new { Category = g.Key, Count = g.Count() })  
                    .Take(3)
                    .ToArray();

// highestCounts[0] is the first count
// highestCounts[1] is the second
// highestCounts[2] is the third
// make sure to handle cases where there are less than 3 items!

作为一个FYI,如果你某一天只需要第N个值而不是前三个值,你可以使用enter image description here来访问任意索引的值。