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

问题描述

我有一个包含两个数据点的示例类:

I have an example class containing two data points:

public enum Sort { First, Second, Third, Fourth }
public class MyClass
{
    public MyClass(Sort sort, string name) {
        this.Sort = sort;
        this.Name = name;
    }

    public Sort Sort { get; set; }
    public string Name { get; set; }
}

我希望通过它们的Sort属性将它们分组,然后按字母顺序排列这些组.

I'm looking to sort them into groups by their Sort property, and then alphabetize those groups.

List<MyClass> list = new List<MyClass>() {
    new MyClass(MyClass.Sort.Third, "B"),
    new MyClass(MyClass.Sort.First, "D"),
    new MyClass(MyClass.Sort.First, "A"),
    new MyClass(MyClass.Sort.Fourth, "C"),
    new MyClass(MyClass.Sort.First, "AB"),
    new MyClass(MyClass.Sort.Second, "Z"),
};

输出将是:(显示Name)

A
AB
D
Z
B
C

我已经能够通过使用foreach将项目分成许多较小的数组(按枚举值分组)来做到这一点,但这似乎很繁琐-我认为一定有一些我不愿意使用的LINQ解决方案不知道.

I've been able to do this by using a foreach to separate the items into many smaller arrays (grouped by the enum value) but this seems very tedious - and I think there must be some LINQ solution that I don't know about.

推荐答案

使用扩展方法,首先OrderBy枚举,ThenBy名称.

Using extension methods, first OrderBy the enum, ThenBy name.

var sorted = list.OrderBy( m => m.Sort ).ThenBy( m => m.Name );

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

07-18 16:54