C# 从类中获取不同的类别名称
我的班级结构如下:-C# 从类中获取不同的类别名称,c#,C#,我的班级结构如下:- public class Gallery { private string _category; public string Category { get { return _category; }
public class Gallery
{
private string _category;
public string Category
{
get
{
return _category;
}
set
{
_category = value;
}
}
}
我创建了如下列表对象:-list GalleryList=new list()代码>
我已从sharepoint列表中将项目添加到此列表对象。现在,我需要这个列表对象的不同类别名称。我尝试了GalleryList.Distinct()
。但是我犯了一个错误。如果有人知道答案,请帮助我。如果您只需要类别名称,您需要从图库列表中投影到一系列类别名称,然后使用Distinct
:
// Variable name changed to match C# conventions
List<Gallery> galleryList = ...;
IEnumerable<string> distinctCategories = galleryList.Select(x => x.Category)
.Distinct();
还有
请注意,调用galleryList.Distinct()
本身应该进行编译(如果您有using
指令),但它只是通过引用比较对象,因为您没有覆盖Equals
/GetHashCode
如果您确实需要一组库,所有库都有不同的类别,那么您可以使用具有DistinctBy
方法的库:
IEnumerable<Gallery> distinct = galleryList.DistinctBy(x => x.Category);
“我有错误”不会给我们任何信息…请同时说明错误,以便其他人有更多机会帮助您哇,嗨,Jon大师..我试过'List DistinctCategory=GalleryList.Select(x=>x.Category).Distinct().ToList();'它正在工作。谢谢。我错过了使用system.Linq。这就是问题所在。就其本身而言,它不会编译-
DistinctBy
不是LINQ的一部分。它是MoreLINQ的一部分,我敢说是其他一些图书馆,但你没有提到过类似的东西。
IEnumerable<Gallery> distinct = galleryList.DistinctBy(x => x.Category);
public class Gallery
{
public string Category { get; set; }
}
GalleryList.DistinctBy(x => x._category);