2

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?

2
  • Except the title is very missleading. I can get only one object from "a given object". Edited the title. Commented Dec 26, 2017 at 19:26
  • 1
    Not my title, was edited Commented Dec 26, 2017 at 19:27

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

6 Comments

Working fine thanks. List <Hotel> hotels = Model .Select(r => r.hotel) .GroupBy(h => h.IdHotel) .Select(g => g.First()) .ToList();
Not sure why you care to answer a question with absolutely no attempt and thousands of examples/duplicates
@CamiloTerevinto I did it the same exact reason why you decided to comment on the answer rather than closing the question as a duplicate of one of the "thousands of examples/duplicates." I mean, a meaningful duplicate is hard to find.
@CamiloTerevinto As far as "no attempt" goes, I have no doubt that OP can write his "loop and compare" strategy without a problem.
But there could be far better ways if we at least knew how he is getting the List<ResultsVM> in the first place. So I do doubt their skills to do this with a simple foreach
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.