[英]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:我创建了以下视图模型,用于从我的数据库中获取单个列表中 3 个表的所有结果:
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
然后我通过我的查看结果
ResultsVM
列表
@model List <ResultsVM>
Now I'm trying to extract from this list a new list with the distinct object Hotel
.现在我试图从这个列表中提取一个具有不同对象
Hotel
的新列表。
Is there a way to achieve it with Linq or shall I make a loop and compare them one by one?有没有办法用 Linq 实现它,或者我应该做一个循环并一一比较它们?
Assuming that Hotel
objects have unique IDs, you could get distinct hotels with this LINQ query:假设
Hotel
对象具有唯一 ID,您可以使用以下 LINQ 查询获得不同的酒店:
List<ResultsVM> results = ...
var hotels = results
.Select(r => r.Hotel)
.GroupBy(h => h.HotelId)
.Select(g => g.First())
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.