【问题标题】:How can I sort distinct vals in LINQ (C#)?如何在 LINQ (C#) 中对不同的 val 进行排序?
【发布时间】:2015-11-06 18:19:42
【问题描述】:

我有这个 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”接受类型的第一个参数 可以找到“字符串”(您是否缺少 using 指令或 程序集参考?)

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

【问题讨论】:

    标签: c# linq generic-list distinct-values


    【解决方案1】:

    问题是你已经投射了ItemDescription的属性,所以现在是IEnumerable&lt;String&gt;,所以你只需要按它的项目订购:-

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        相反,您可以听从this answer 的建议:

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

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

        这将按排序顺序返回List&lt;string&gt;

        【讨论】:

          猜你喜欢
          • 2016-05-30
          • 2013-09-03
          • 1970-01-01
          • 1970-01-01
          • 2011-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多