Esempio n. 1
0
        /// <summary>
        /// Produce a new list which is sorted like the given list. Sorting equality is performed by the given function.
        /// This function has poor performance.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="original"></param>
        /// <param name="sortByList"></param>
        /// <param name="equalityFunction"></param>
        /// <param name="excessOption"></param>
        /// <returns></returns>
        public static IList <T> SortByWithEqualityFunction <T, V>(this IList <T> original, IList <V> sortByList,
                                                                  Func <T, V, bool> equalityFunction, SortByExcessOption excessOption = SortByExcessOption.PlaceAtEnd)
        {
            //First, do the VERY inefficient sorted insertion into the new list (while removing the elements from the old one)
            var newList      = new List <T>();
            var originalCopy = new List <T>(original);

            foreach (V element in sortByList)
            {
                try
                {
                    //If this fails, it triggers the try/catch and thus we don't add or remove the elements
                    var originalElement = originalCopy.First(x => equalityFunction(x, element));
                    newList.Add(originalElement);
                    originalCopy.Remove(originalElement);
                }
                catch { }
            }

            //Next, figure out what to do with the rest.
            if (originalCopy.Count > 0)
            {
                if (excessOption == SortByExcessOption.PlaceAtBeginning)
                {
                    var sortedElements = newList;
                    newList = originalCopy.ToList();
                    newList.AddRange(sortedElements);
                }
                else if (excessOption == SortByExcessOption.PlaceAtEnd)
                {
                    newList.AddRange(originalCopy);
                }
            }

            return(newList);
        }
Esempio n. 2
0
 /// <summary>
 /// Produce a new list which is sorted like the given list. This function is not highly performant (O(n^2)),
 /// but it gets the job done.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="original"></param>
 /// <param name="sortByList"></param>
 /// <returns></returns>
 public static IList <T> SortBy <T>(this IList <T> original, IList <T> sortByList, SortByExcessOption excessOption = SortByExcessOption.PlaceAtEnd)
 {
     return(original.SortByWithEqualityFunction(sortByList, (T x, T y) => x.Equals(y), excessOption));
 }