我有一个IGrouping类型的对象,并希望在不改变对象类型的情况下对组内的元素进行排序。
换句话说,我有
var tmp = group.OrderBy(x => x);
group
类型为IGrouping<int, someanonymousclass>
,我希望tmp
的类型为IGrouping<int, someanonymousclass>
。
一种解决方法是将其更改为Dictionary或新的匿名类,但我希望tmp具体为IGrouping<int, someanonymousclass>
类型。
换句话说:我想对我的IGrouping<int, someanonymousclass>
对象的元素进行排序。如果我使用OrderBy
,则会将group
的类型更改为IOrderedEnumerable
,我无法再访问group.Key
。我怎样才能维持group
的类型?
示例:
var states = SimulationPanel.innerPanel.Children.OfType<StateBar>().Where(x => x.isSensorState())
.GroupBy(x => (SensorElement)x.BauplanElement,
x => new
{
Start = (decimal)(x.Margin.Left / SimulationPanel.Zoom),
Width = (decimal)(x.Width / SimulationPanel.Zoom),
State = x.State
});
var group = states.First();
var tmp = group.OrderBy(x => x.Start);
var key = tmp.Key; //This does not work, because tmp is not of type IGrouping
我知道在分组之前我可以使用OrderBy
。不过,我不想这样做。
答案 0 :(得分:8)
如果可以,只需提前订购,例如
var states = SimulationPanel.innerPanel
.Children
.OfType<StateBar>()
.Where(x => x.isSensorState())
.OrderBy(x => (decimal)(x.Margin.Left / SimulationPanel.Zoom))
.GroupBy(...);
(或者在Select
之前加OrderBy
并使GroupBy
更简单。)
如果你真的需要这个,你可以编写自己的IGrouping<TKey, TElement>
实现和扩展方法来对元素进行排序并将它们保留在列表中:
public static class GroupExtensions
{
public IGrouping<TKey, TElement, TOrderKey> OrderBy
(this IGrouping<TKey, TElement> grouping,
Func<TElement, TOrderKey> orderKeySelector)
{
return new GroupingImpl<TKey, TElement>
(grouping.Key, grouping.OrderBy(orderKeySelector));
}
private class GroupingImpl<TKey, TElement> : IGrouping<TKey, TElement>
{
private readonly TKey key;
private readonly List<TElement> elements;
internal GroupingImpl(TKey key, IEnumerable<TElement> elements)
{
this.key = key;
this.elements = elements.ToList();
}
public TKey Key { get { return key; } }
public IEnumerator<TElement> GetEnumerator()
{
return elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}