Linq OrderBy against specific values

后端 未结 8 1737
悲&欢浪女
悲&欢浪女 2020-12-04 17:41

Is there a way in Linq to do an OrderBy against a set of values (strings in this case) without knowing the order of the values?

Consider this data:

A         


        
8条回答
  •  盖世英雄少女心
    2020-12-04 18:20

    Not really efficient for large lists but fairly easy to read:

    public class FixedOrderComparer : IComparer
    {
        private readonly T[] fixedOrderItems;
    
        public FixedOrderComparer(params T[] fixedOrderItems)
        {
            this.fixedOrderItems = fixedOrderItems;
        }
    
        public int Compare(T x, T y)
        {
            var xIndex = Array.IndexOf(fixedOrderItems, x);
            var yIndex = Array.IndexOf(fixedOrderItems, y);
            xIndex = xIndex == -1 ? int.MaxValue : xIndex;
            yIndex = yIndex == -1 ? int.MaxValue : yIndex;
            return xIndex.CompareTo(yIndex);
        }
    }
    

    Usage:

    var orderedData = data.OrderBy(x => x, new FixedOrderComparer("A", "B", "C"));
    

    Note: Array.IndexOf(....) uses EqualityComparer.Default to find the target index.

提交回复
热议问题