Linq Orderby和与众不同 [英] Linq orderby and distinct
问题描述
我的表格设置如下:
Section SectionOrder
Sect1 1
Sect2 2
Sect3 3
Sect3 3
Sect1 1
Sect2 2
我需要按正确的部分顺序拉出不同的部分.这是我正在使用的linq,但是由于某种原因,它并没有按正确的顺序排列它们.
I need to pull out distinct sections in correct section order. Here is the linq that I'm using, but it's not putting them in the correct order for some reason.
var myVar = (from x in context.Documents
orderby x.SectionOrder ascending
select x.Section).Distinct();
然后,我希望能够遍历myVar并将每个项目放在列表中,如下所示:
I then want to be able to loop through myVar and put each item in a list as follows:
foreach (var t in myVar)
{
listOfDocTypeSections.Add(t);
}
推荐答案
OrderBy
和Distinct
的顺序很重要:虽然OrderBy
产生了有序序列,但Distinct
却没有.您需要先放置Distinct
,然后再使用OrderBy
.但是,由于您在一个属性上使用Distinct
,在另一个属性上进行排序,因此您需要以不同的方式进行操作:
The ordering of OrderBy
and Distinct
matters: while OrderBy
produced an ordered sequence, Distinct
doesn't. You need to put Distinct
first, and then use OrderBy
. However, since you take Distinct
on one attribute, and order on the other attribute, you need to do it differently:
var myVar = context
.Documents
.GroupBy(x => x => x.Section) // This replaces Distinct()
.OrderBy(g => g.FirstOrDefault().SectionOrder) // There will be no default
.Select(g => g.Key);
此方法将Distinct
替换为GroupBy
,并在组的第一个SectionOrder
项目上下订单.您可以更改此排序策略以对Section
中的其他某些项进行排序,例如SectionOrder
的Min
或Max
值:
This approach replaces Distinct
with GroupBy
, and orders on the first SectionOrder
item of a group. You can change this sorting strategy to sort on some other item within the Section
, say, Min
or Max
value of SectionOrder
:
var myVar = context
.Documents
.GroupBy(x => x => x.Section)
.OrderBy(g => g.Max(x => x.SectionOrder))
.Select(g => g.Key);
这篇关于Linq Orderby和与众不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!