如何在 LINQ (C#) 中对不同的值进行排序?

How can I sort distinct vals in LINQ (C#)?

我有这个 LINQ 可以从通用列表中获取特定 class 成员的不同值:

var distinctDescriptions = itemsForMonthYearList.Select(x => x.ItemDescription).Distinct();

通用列表是这样定义的:

List<ItemsForMonthYear> itemsForMonthYearList;

class是:

public class ItemsForMonthYear
{
    public String ItemDescription { get; set; }
    public String monthYr { get; set; }
    public int TotalPackages { get; set; }
    public Decimal TotalPurchases { get; set; }
    public Decimal AveragePrice { get; set; }
    public Double PercentOfTotal { get; set; }
}

我认为这行得通:

var distinctDescriptions = itemsForMonthYearList.Select(x => x.ItemDescription).Distinct().OrderBy(x => x.ItemDescription);

...但它甚至无法编译:

"'string' does not contain a definition for 'ItemDescription' and no extension method 'ItemDescription' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)"

如何按字母顺序对不同的值进行排序?

问题是您已经投影了 属性 ItemDescription,所以现在是 IEnumerable<String>,所以您只需要按它的项目排序:-

var distinctDescriptions = itemsForMonthYearList.Select(x => x.ItemDescription)
                                                .Distinct()
                                                .OrderBy(x => x);

您只投影了一个 属性 类型 string,因此,结果是一个 string 集合。试试这个:

var distinctDescriptions = itemsForMonthYearList.Select(x => x.ItemDescription).Distinct().OrderBy(x => x);

正如其他人已经提到的,您的 Select 将 属性 投影到字符串集合中,而字符串没有 ItemDescription 属性,因此您可以'按此顺序。

相反,您可以遵循 this answer 的建议:

Select return 集合转换为列表,然后对其进行排序。

var distinctDescriptions = itemsForMonthYearList.Select(x => x.ItemDescription).Distinct().ToList();
distinctDescriptions.Sort();

这将 return 一个 List<string> 排序。