Search code examples
c#linqgeneric-listdistinct-values

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:

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?)"

How can I sort the distinct values alphabetically?


Solution

  • 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:-

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