简体   繁体   English

使用 Linq 从复杂的 object 中提取不同的对象

[英]Extracting distinct objects from a complex object using Linq

I have a collection that contains a list of complex objects, "SubCategory".我有一个包含复杂对象列表“子类别”的集合。 SubCategory contains "Category".子类别包含“类别”。

I can iterate through my collection and see all object, and drill down through to Category.我可以遍历我的集合并查看所有 object,然后深入到类别。

How can I, using Linq, extract a distinct list of Categories?如何使用 Linq 提取不同的类别列表?

I initially tried this in a foreach loop:我最初在 foreach 循环中尝试了这个:

if (!categoryList.Contains(baseline.ContentCategory)
{
    categoryList.Add(baseline.ContentCategory);
}

But that just does not work, and I think a Linq solution would be more elegant.但这不起作用,我认为 Linq 解决方案会更优雅。

Thanks.谢谢。

subCategoryList.Select(s => s.Category).Distinct() subCategoryList.Select(s => s.Category).Distinct()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM