Hinek
Hinek

Reputation: 9729

Find distinct categories of all elements using LINQ

I have two data classes:

public class Category
{
    public string Title { get; set; }
    public int OrderNo { get; set; }
}

public class Element
{
    public string Prop1 { get; set; }
    // ...
    public string PropN { get; set; }

    public Category Category { get; set; }
}

Given an enumeration of Element-objects, I need a distinct enumeration of Category Title-strings ordered by OrderNo.

If I had an enumeration of Category-objects, this would be something like:

var catTitles = categories.OrderBy(cat => cat.OrderNo).Select(cat => cat.Title).Distinct();

But I only have a enumeration of Element-object, which reference their Category-objects ... is there a simple way to extract them via LINQ?

Upvotes: 0

Views: 204

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

Nearly the same way, you need to select the Category:

var query = elements
    .OrderBy(el => el.Category.OrderNo)
    .Select(el => el.Category.Title)
    .Distinct();

If the category can be null:

var query = elements
    .OrderBy(el => el.Category == null ? int.MaxValue : el.Category.OrderNo)
    .Select(el => el.Category == null ? null : el.Category.Title)
    .Distinct();

Upvotes: 2

Selman Genç
Selman Genç

Reputation: 101681

elementList.Select(x => x.Category)
           .OrderBy(x => x.OrderNo)
           .Select(x => x.Title)
           .Distinct();

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

var Result = categories.GroupBy(p=> p.Category).Select(group => group.OrderByDescending(d=> d.OrderNo)).ToList();

Upvotes: 0

Related Questions