Loop through a subset then the main set C#, Razor, linq, Umbraco

68 views Asked by At

I am trying to add a featured items feature to my page in umbraco where people can add the pages they want to highlight and then compare those IDs with the search results and output the featured items first then iterate through the rest of the results.

So I have

@foreach (var property in Model.SearchResults.Properties)
{}

and I know I can use Linq to do a where for the ID array but how would I then iterate through the rest of the items? Would I need two loops? One with the IDs included and one with them excluded?

e.g.

var allPropeties = Model.SearchResults.Properties();
var featuredIDs= new [1,22,55,84,1234];
var featuredItems= allProperties.Where(x => featuredIDs.Contains(x.Id)).ToArray();

I'm new to C# and Linq so I'm not sure of the flexibility yet. apologies if this is a duplicate of another question but I couldn't find it anywhere!

Umbraco consumes our property management software, each property has a unique ID as well as property data such as addresses, images etc... the API dumps that info,1 page per property on Umbraco. The code to consume that info and output in the search is there.

We currently output the property search/listing page using the simple foreach at the top of the question.

What I'm trying to work out is if I can force this to output the featured properties first or if I have to separate the logic and loop through featured if they exist then output the rest excluding the featured list.

var allPropeties = Model.SearchResults.Properties();
if(Model.Content.FeaturedProps){
var featuredIDs= Model.Content.FeaturedProps;
var featuredItems= allProperties.Where(x => featuredIDs.Contains(x.Id));
}

The goal is to add 5 - 10 featured properties per listing page as seen on our website

1

There are 1 answers

5
Lajos Arpad On

Since you want all records in the results and you want to order them descendingly by their id being contained by the set. So, instead of the Where, we will need OrderByDescending:

.OrderByDescending(x => featureIDs.Contains(x.Id))

You were using the right condition in the wrong clause.