从类中获取不同的类别名称

本文关键字:别名 获取 | 更新日期: 2023-09-27 17:57:47

我有一个具有以下结构的类:-

  public class Gallery
{
         private string _category;
            public string Category
                {
                    get
                    {
                        return _category;
                    }
                    set
                    {
                        _category = value;
                    }
                }
        }

我创建了一个列表对象,如下所示:-List<Gallery> GalleryList = new List<Gallery>();我已将共享点列表中的项目添加到此列表对象。现在我需要这个列表对象的不同类别名称。我试过GalleryList.Distinct()。但是我犯了错误。如果有人知道答案,请帮帮我。

从类中获取不同的类别名称

如果你只需要类别名称,你需要从画廊列表中投影到一系列类别名称-然后Distinct就可以了:

// Variable name changed to match C# conventions
List<Gallery> galleryList = ...;
IEnumerable<string> distinctCategories = galleryList.Select(x => x.Category)
                                                    .Distinct();

如果您想要一个List<string>,只需在末尾添加一个对ToList的调用即可。

您需要一个using指令:

using System.Linq;

同样。

请注意,调用galleryList.Distinct()本身应该编译(如果您有using指令),但它只是通过引用比较对象,因为您还没有重写Equals/GetHashCode

如果你真的需要一个画廊集合,所有这些画廊都有不同的类别,那么你可以使用MoreLINQ,它有一个DistinctBy方法:

IEnumerable<Gallery> distinct = galleryList.DistinctBy(x => x.Category);

在这种情况下,MoreLinq命名空间需要一个using指令。

您还应该了解自动实现的属性。您的Gallery类可以更简洁地写成:

public class Gallery
{
    public string Category { get; set; }
}
GalleryList.DistinctBy(x => x._category);