简体   繁体   English

LINQ-选择不同的子对象

[英]c# LINQ - Selecting distinct sub object

I have the following object structure represented by c# classes: 我有以下由c#类表示的对象结构:

[
    {
        Title: "",
        Year: 1977,
        Categories: ["Action", "Adventure", "Fantasy"],
        Score: 96
    }
]

This json is serialized to an IEnumerable<TitleItem> object, where Categories is an IList<string> object. 此json序列化为IEnumerable<TitleItem>对象,其中CategoriesIList<string>对象。

From that collection of TitleItem objects I would like to get a new IList<string> of distinct categories. TitleItem对象的那个集合中,我想获得一个新的IList<string>不同类别的对象。 How can this be done? 如何才能做到这一点?

collection.SelectMany(x=>x.Categories).District().ToList()

您可以使用SelectMany来“拼合”类别列表,然后使用Distinct

var result = titleItems.SelectMany(item => item.Categories).Distinct().ToList();

You can do a SelectMany and then a distinct on that IEnumerable : 您可以执行一个SelectMany ,然后对该IEnumerable进行distinct

IEnumerable<TitleItem> items = getItemsFromSomeWhere();
var uniqueTitles = items.SelectMany(i => i.Categories).Distinct().ToList();

Here is the query that will return distinct of categories 这是将返回不同类别的查询

class TitleItem {
    public string Title;
    public string Year;
    public float score;
    public IList<string> Categories;
}

var titleItems = new List<TitleItem>();
var titleItem1 = new TitleItem();
titleItem1.Categories = new List<string>();
titleItem1.Categories.Add("Action");
titleItem1.Categories.Add("Adventure");
titleItem1.Categories.Add("Fantasy");
titleItem1.Categories.Add("Action");
titleItems.Add(titleItem1);

var titleItem2 = new TitleItem();
titleItem2.Categories = new List<string>();
titleItem2.Categories.Add("Action");

titleItems.SelectMany(a => a.Categories).Distinct();

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

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