/// <summary> /// Multisorts an enumeration of posts applied in order /// </summary> /// <param name="posts"></param> /// <param name="options"></param> /// <returns>sorted posts</returns> public static IEnumerable <Post> SortBy(this IEnumerable <Post> posts, SortOptions options) { if (options == null) { return(posts); } var sorters = options.GetKeyValuePairs() .Where(sorter => { var validSorterProperties = new string[] { "pricePerUnit", "price" }; if (!validSorterProperties.Contains(sorter.Key)) { return(false); } var validSorterOrder = new string[] { "asc", "desc" }; if (!validSorterOrder.Contains(sorter.Value)) { return(false); } return(true); }); return(sorters.Count() <= 0 ? posts : posts.Aggregate(new List <Post>(), (acc, post) => { acc.Add(post); foreach (var sorter in sorters) { var sorterType = sorter.Value; if (sorter.Key == "pricePerUnit") { if (sorterType == "asc") { acc = acc.OrderBy(post => post.PricePerUnit).ToList(); } if (sorterType == "desc") { acc = acc.OrderByDescending(post => post.PricePerUnit).ToList(); } } if (sorter.Key == "price") { if (sorterType == "asc") { acc = acc.OrderBy(order => order.Article.Price).ToList(); } if (sorterType == "desc") { acc = acc.OrderByDescending(order => order.Article.Price).ToList(); } } } return acc; })); }