如何对多个列表属性进行排序? [英] How to sort multiple list properties?

查看:81
本文介绍了如何对多个列表属性进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表列表myList,它具有1200万个元素.myClass具有两个属性,即."gt"和"gm".我想找到最大的"gt"元素,然后选择最小的"gm".例如:让 myList 如:(第一列是 gt 其他是 gm)

I have list list myList which has over 12 million elements. myClass has two properties ie. "gt" and "gm". I want to find maximum "gt" elements and choose that has min "gm". forexample: let myList such as:(first column is gt other is gm)

  4 1
  5 2
  7 1
  8 3
  4 3
  2 2
  8 7
  1 7
  8 2

我想获取具有gt = 8,gm = 2的myClass元素.我可以从哪里开始?按有效的方式对gt降序进行排序?

I want to get the myClass element which has gt=8,gm=2. Where can I start?is sorting gt descending order an efficent way?

推荐答案

myList.OrderByDescending(x => x.gt)                                  
      .ThenBy(x => x.gm)
      .First();

一种更有效,但读取量更少的方法是使用 Enumerable.Aggregate ,该方法将集合迭代一次,从而在O(n)时间内执行:

A more efficient, but less readbale way would be using Enumerable.Aggregate which iterates the collection once, and thus executes in O(n) time:

var seed = myList.First()
myList.Aggregate(seed, 
        (max, item) => {
            if(item.gt > max.gt)
                return item;
            if(item.gt == max.gt && item.gm < max.gm)
                return item;
            return max;
        });

在采用更有效的方法之前,请同时进行两项测量并确保在可读性-性能之间进行权衡是值得的.

Before going with the more efficient approach, measure both and make sure the readability-performance trade-off is worth it.

这篇关于如何对多个列表属性进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆