Example #1
0
        public static IEnumerable <Post> FilterBy(this IEnumerable <Post> posts, FilterOptions options)
        {
            if (options == null)
            {
                return(posts);
            }

            var filters = options.GetKeyValuePairs()
                          .Where(filter =>
            {
                var validFilterProperties = new string[] { "pricePerUnit", "price" };
                if (!validFilterProperties.Contains(filter.Key))
                {
                    return(false);
                }

                var filterType = filter.Value.Substring(0, 3);

                var validFilterTypes = new string[] { "$lt", "$gt", "$eq" };
                if (!validFilterTypes.Contains(filterType))
                {
                    return(false);
                }

                return(true);
            });

            return(filters.Count() <= 0
                ? posts
                : posts.Where(post =>
            {
                var result = false;

                foreach (var filter in filters)
                {
                    var filterType = filter.Value.Substring(0, 3);
                    var filterValue = filter.Value.Replace(filterType, string.Empty);

                    if (filter.Key == "pricePerUnit")
                    {
                        var value = decimal.Parse(filterValue, CultureInfo.InvariantCulture);
                        if (filterType == "$gt")
                        {
                            return post.PricePerUnit > value;
                        }
                        if (filterType == "$lt")
                        {
                            return post.PricePerUnit < value;
                        }
                        if (filterType == "$eq")
                        {
                            return post.PricePerUnit == value;
                        }
                        return false;
                    }

                    if (filter.Key == "price")
                    {
                        var value = decimal.Parse(filterValue, CultureInfo.InvariantCulture);
                        if (filterType == "$gt")
                        {
                            return post.Article.Price > value;
                        }
                        if (filterType == "$lt")
                        {
                            return post.Article.Price < value;
                        }
                        if (filterType == "$eq")
                        {
                            return post.Article.Price == value;
                        }
                        return false;
                    }
                }

                return result;
            }));
        }