如何对特定案例的列表进行排序c#

本文关键字:列表 排序 案例 | 更新日期: 2023-09-27 18:28:15

这里有一个示例代码,我希望以这样的取消排序顺序获得TotalCharge属性上的排序数据。

//List<RateStatus> SortedList =  objListOrder.OrderByDescending(o=>o.TotalCharge).ToList();

请参阅下面的代码,并指导我如何在取消订阅中对TotalCharge属性进行排序。感谢

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            List<RateStatus> oRateCollection = new List<RateStatus>();
            RateStatus oRateStatus = new RateStatus();
            oRateStatus.StatusMsg = "Ok";
            oRateStatus.ErrorMsg = "None";
            oRateStatus.RateDetails.Add(new RateDetails()
            {
                CurrentcyCode = "GBP",
                TotalCharge = 20
            });
            oRateCollection.Add(oRateStatus);
           // i want something like this below
           //List<RateStatus> SortedList =  objListOrder.OrderByDescending(o=>o.TotalCharge).ToList();
        }
    }
    public class RateStatus
    {
        public RateStatus()
        {
            RateDetails = new List<RateDetails>();
        }
        public string StatusMsg
        {
            get;
            set;
        }
        public string ErrorMsg
        {
            get;
            set;
        }
        public List<RateDetails> RateDetails
        {
            get;
            set;
        }
    }
    public class RateDetails
    {
        public string ServiceCode
        {
            get;
            set;
        }
        public string ServiceName
        {
            get;
            set;
        }
        public string CurrentcyCode
        {
            get;
            set;
        }
        public double TotalCharge
        {
            get;
            set;
        }
    }

它是这样排序的

oRateStatus.RateDetails.Sort(new RateStatusComparer());
oRateCollection.Add(oRateStatus);

public class RateStatusComparer : IComparer<RateDetails>
    {
        public int Compare(RateDetails x, RateDetails y)
        {
            if (x.TotalCharge > y.TotalCharge) return -1;
            else if (x.TotalCharge < y.TotalCharge) return 1;
            else return 0;
        }
    }

感谢

如何对特定案例的列表进行排序c#

创建一个实现IComparer<RateStatus>的类。

例如,类似这样的东西:

public class RateStatusComparer: IComparer<RateStatus>
{
    public int Compare(RateStatus x, RateStatus y)
    {
        ... your comparing code here
    }
}

然后你可以使用List.Sort的过载,并提供类似的比较器

var с = new RateStatusComparer();
objListOrder.Sort(c);

有关详细信息,请参阅MSDN。

下面是代码

由于Total charge是一个数值,我们可以使用Min和Max方法进行排序。

下降:

List<RateStatus> SortedList = oRateCollection.OrderByDescending(o => o.RateDetails.Max(r => r.TotalCharge)).ToList();