[英]How can I fix this LINQ so that it treats a pairs of vals as a distinct value?
[英]How can I sort distinct vals in LINQ (C#)?
我有此LINQ可以從通用列表中獲取特定類成員的不同值:
var distinctDescriptions = itemsForMonthYearList.Select(x => x.ItemDescription).Distinct();
通用列表是通過以下方式定義的:
List<ItemsForMonthYear> itemsForMonthYearList;
該類是:
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'不包含'ItemDescription'的定義,找不到擴展方法'ItemDescription'接受類型為'string'的第一個參數(您是否缺少using指令或程序集引用?) ”
如何按字母順序對不同的值排序?
問題是您已經投影了屬性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
到字符串集合中,並且字符串沒有ItemDescription
屬性,因此您不能以此排序。
相反,您可以按照以下答案的建議進行操作:
將“ Select
返回集合轉換為“列表”,然后進行排序。
var distinctDescriptions = itemsForMonthYearList.Select(x => x.ItemDescription).Distinct().ToList();
distinctDescriptions.Sort();
這將按排序順序返回List<string>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.