Object.CategoryName into List<string> of category names
I have List<MyObject> listObjects
where I would like a unique list of MyObject.CategoryName
as List&开发者_开发技巧lt;string>
.
I have the following linq so far.
var categoryNames = from element in listObjects
orderby element.CategoryName
group element by element.CategoryName;
However, var categoryNames
is a IEnumerable<IGrouping<string, MyObject>>
.
How can I get the list as a List<string>
?
thank you.
var categoryNames = listObjects.Select(x => x.CategoryName).Distinct().ToList();
In words: "Grab only the category names, and then ignore duplicates, and put them into a list."
var categoryNames = listObjects.Select(o=>o.CategoryName).Distinct().ToList()
精彩评论