简体   繁体   English

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

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

I've got this LINQ to get the distinct values of a particular class member from a generic list: 我有此LINQ可以从通用列表中获取特定类成员的不同值:

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

The generic list is defined this way: 通用列表是通过以下方式定义的:

List<ItemsForMonthYear> itemsForMonthYearList;

The class is: 该类是:

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; }
}

I thought this would work: 我认为这可以工作:

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

...but it doesn't even compile: ...但是它甚至不能编译:

" '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?) " 'string'不包含'ItemDescription'的定义,找不到扩展方法'ItemDescription'接受类型为'string'的第一个参数(您是否缺少using指令或程序集引用?)

How can I sort the distinct values alphabetically? 如何按字母顺序对不同的值排序?

The problem is you have already projected the property ItemDescription so it is IEnumerable<String> now, so you simply need to order by it's items:- 问题是您已经投影了属性ItemDescription所以现在它是IEnumerable<String> ,因此您只需要按其项进行排序:

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

You are projecting only one property of type string , so, the result is a string collection. 您仅投影了string类型的一个属性,因此,结果是一个string集合。 Try this: 尝试这个:

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

As others have already mentioned, your Select projects the property into collection of strings, and strings don't have an ItemDescription property, so you can't order by that. 正如其他人已经提到的那样,您的Select将属性ItemDescription到字符串集合中,并且字符串没有ItemDescription属性,因此您不能以此排序。

Instead, you can follow the advice from this answer : 相反,您可以按照以下答案的建议进行操作:

Convert the Select return collection to a List, then sort that. 将“ Select返回集合转换为“列表”,然后进行排序。

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

This will return a List<string> in sorted order. 这将按排序顺序返回List<string>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM