linq 如何在不更改IGrouping类型的情况下对其进行排序?

68de4m5k  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(148)

我有一个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。但我不想这样做。

3phpmpom

3phpmpom1#

如果你可以的话,就把订单提前一点,例如:

var states = SimulationPanel.innerPanel
       .Children
       .OfType<StateBar>()
       .Where(x => x.isSensorState())
       .OrderBy(x => (decimal)(x.Margin.Left / SimulationPanel.Zoom))
       .GroupBy(...);

(Or将Select放在OrderBy之前,使GroupBy更简单。)
如果确实需要这样做,可以编写自己的IGrouping<TKey, TElement>实现和一个扩展方法来对元素进行排序并将它们保留在列表中:

public static class GroupExtensions
{
    public static IGrouping<TKey, TElement> OrderGroupingBy<TKey, TElement, TOrderKey>
        (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();
        }
    }
}

相关问题