[英]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
? 如何按给定
TagType
的Tags
Value
对Questions
进行排序? The problem here being that a Question
can have many Tags
of a given TagType
. 这里的问题是一个
Question
可以具有给定TagType
许多Tags
。 In the event of a Question
having multiple Tags
(which is mostly unusual in my scenario), I just care about the first Tag
. 如果
Question
具有多个Tags
(在我的情况下通常不常见),那么我只关心第一个Tag
。
Here's an example data table output where TagTypes have their own columns: 这是数据表输出示例,其中TagType具有自己的列:
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? 给定
IQueryable<Question>
,可以将什么表达式发送到Queryable.OrderBy(...)
以实现我的目标?
Enumerable.OrderBy(x => x.Tags.Where(x => x.TagType == aTagType).First().Value);
Thanks to @James for the suggestion but that didn't work. 感谢@James的建议,但这没有用。 The solution is to use
Min
and Max
for the field of the child collection to be ordered by: 解决方案是将
Min
和Max
用于Max
的字段,排序方式如下:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.