Pierre Anken
Pierre Anken

Reputation: 336

How can I get distinct objects extracted from a property of a list of objects?

I created following viewmodel for getting from my DB all the results from 3 tables in a single list:

public class ResultsVM
{
    public Room room { get; set; }
    public Hotel hotel { get; set; }
    public List<Picture> pictures { get; set; }
}

I'm then passing my View a list of ResultsVM

@model List <ResultsVM>

Now I'm trying to extract from this list a new list with the distinct object Hotel.

Is there a way to achieve it with Linq or shall I make a loop and compare them one by one?

Upvotes: 2

Views: 74

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Assuming that Hotel objects have unique IDs, you could get distinct hotels with this LINQ query:

List<ResultsVM> results = ...
var hotels = results
    .Select(r => r.Hotel)
    .GroupBy(h => h.HotelId)
    .Select(g => g.First())
    .ToList();

Upvotes: 2

Related Questions