コード例 #1
0
        public void TestNullComparer_BuildComparer()
        {
            Random random = new Random();

            // build a list of random dates
            var dates = new List <DateTime>(getRandomDates(random));

            // randomly choose which order to sort the components by
            string[] propertyNames = { "Year", "Month", "Day", "Hour", "Minute", "Second" };
            randomShuffle(propertyNames, random);

            // build a comparer based on the order of the components
            IComparer <DateTime> dateComparer = NullComparer <DateTime> .Default;

            foreach (string propertyName in propertyNames)
            {
                string current = propertyName; // avoids non-local lambda problem
                Func <DateTime, object> getter = (DateTime d) => typeof(DateTime).GetProperty(current).GetValue(d, null);
                bool ascending = random.Next() % 2 == 0;
                if (ascending)
                {
                    dateComparer = dateComparer.ThenBy(getter);
                }
                else
                {
                    dateComparer = dateComparer.ThenByDescending(getter);
                }
            }

            // now we can sort the dates accordingly
            dates.Sort(dateComparer);
        }
コード例 #2
0
 public static IComparer <T> Defer <T>(this IComparer <T> first, Predicate <T> test) =>
 first.ThenByDescending(new TestComparer <T>(test));