I have the following object structure represented by c# classes:
[
{
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.
From that collection of TitleItem
objects I would like to get a new IList<string>
of distinct categories. 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
:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.