How do I sort and merge two lists ASP.NET MVC

539 Views Asked by At

I have a list of featured and non-featured items and I'm trying to select and order them so that the featured items are displayed first, then the non featured ones, and all of this ordered by Date.

For some reason this is not working:

var list = (from p in DbContext.Products
                        where p.Featured == true
                        where p.Sold == false
                        where p.Title.Contains(filter)
                        || p.Category.Name.Contains(filter)
                        orderby p.Featured
                        orderby p.CreatedOn descending
                        select new Models.Response.ProductIndexResponse
                        {
                            Id = p.Id,
                            Title = p.Title,
                            Price = p.Price,
                            Image = p.Image,
                            Featured = p.Featured,
                        })
                        .Concat(from p in DbContext.Products
                                where p.Featured == false
                                where p.Sold == false
                                where p.Title.Contains(filter)
                                || p.Category.Name.Contains(filter)
                                select new Models.Response.ProductIndexResponse
                                {
                                    Id = p.Id,
                                    Title = p.Title,
                                    Price = p.Price,
                                    Image = p.Image,
                                    Featured = p.Featured
                                }).ToList();
            return View(list);

It seems like it should work to me. Any ideas on this? Linq is also acceptable.

1

There are 1 best solutions below

0
AudioBubble On

Use Concat and OrderBy

var result = list1.Concat(list2).OrderBy(x => x.Column).ToList();

If you want to remove duplicates and get an unique set of elements you can also use Union method:

var result = list1.Union(list2).OrderBy(x => x.Column).ToList();