Reputation: 9729
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
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
Reputation: 101681
elementList.Select(x => x.Category)
.OrderBy(x => x.OrderNo)
.Select(x => x.Title)
.Distinct();
Upvotes: 1
Reputation: 222582
var Result = categories.GroupBy(p=> p.Category).Select(group => group.OrderByDescending(d=> d.OrderNo)).ToList();
Upvotes: 0