简体   繁体   中英

LINQ to Entities - sorting on child collection with filter

Given the following entities:

Question
 -string Title
 -ICollection<Tag> Tags

Tag
 -string Value
 -string TagType

How can I sort Questions by the Value of Tags of a given TagType ? The problem here being that a Question can have many Tags of a given TagType . In the event of a Question having multiple Tags (which is mostly unusual in my scenario), I just care about the first Tag .

Here's an example data table output where TagTypes have their own columns:

Title (Question.Title) | Topic (TagType) | Module (TagType)
-----------------------------------------------------------
Question 1             | Algebra         | Maths

Given an IQueryable<Question> , what expression can I send to Queryable.OrderBy(...) to achieve my goal?

Enumerable.OrderBy(x => x.Tags.Where(x => x.TagType == aTagType).First().Value);

Thanks to @James for the suggestion but that didn't work. The solution is to use Min and Max for the field of the child collection to be ordered by:

if (sortDescending)
{
    expr = q => q.Tags
        .Where(t => t.TagType.Equals(sortByTagType, StringComparison.CurrentCultureIgnoreCase))
        .Max(t => t.Value);
}
else
{
    expr = q => q.Tags
        .Where(t => t.TagType.Equals(sortByTagType, StringComparison.CurrentCultureIgnoreCase))
        .Min(t => t.Value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM