Question: Retaining order with LINQ using .Contains


Retaining order with LINQ using .Contains

Answers 1
Added at 2017-01-02 11:01

I have read this question about retaining order in a list, but I didn't see anything about using the .Contains() method, hence why I'm asking this questions.

I have created a wrapper class which can contain different objects, like below:

public class RecommenderItem
    public Guid Id { get; set; }
    public object Entity { get; set; }

I have a method which orders a list, regardless of the type of object. Before I call the method which orders this list, I retrieve the objects from my database and map them to RecommenderItem. After this list is ordered, I want to return these items as their original type.

I have succesfully done this, but for the sake of readability, I would like to use LINQ in my entire method. Currently, I'm setting up my output list like this:

var filteredOnContent = ContentBasedFilter.FilterBasedOnContent(ratedItems, itemsNotReviewed); //This is the function which orders the list. Both ratedItems and itemsNotReviewed are lists of RecommenderItems
var restaurantObjects = (from S1 in filteredOnContent
                         from S2 in restaurantsCloseToUser
                         where S1.Id == S2.Id
                         select S2).ToList();

In this example is restaurantsCloseToUser the list that has been retrieved from the database.

I have tried the following, but it doesn't retain the order the filtered list has. This is very important, since the list is a top 10 of recommendations.

var test = restaurantsCloseToUser.Where(x => contentBasedFiltered.Select(r => r.Id).Contains(x.Id)).ToList();

Is there a way I can use LINQ and still retain the order of the filtered list?

Please let me know if I need to provide more information!

nr: #1 dodano: 2017-01-02 11:01

If I understand correctly, contentBasedFiltered is the ordered list and you want the original items from restaurantsCloseToUser but in the order they have in contentBasedFiltered. So I'd try the following:

var test = contentBasedFiltered.Select(x => restaurantsCloseToUser.FirstOrDefault(r => r.Id == x.Id)).ToList();

This returns a list in order of contentBasedFiltered but with the items from restaurantsCloseToUser.

Source Show
◀ Wstecz