Get Distinct Category Name From Class

I have a class with following structure :-

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

I created a list object like this :- List<Gallery> GalleryList = new List<Gallery>(); I have added items to this list object from sharepoint list. Now I need distinct category name from this list object. I tried GalleryList.Distinct() . But I am getting error. Please help me if anyone knows the answer.

Jon Skeet
people
quotationmark

If you just need the category names, you need to project from the list of galleries to a sequence of category names - and then Distinct will work:

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

If you want a List<string>, just add a call to ToList at the end.

You'll need a using directive of:

using System.Linq;

as well.

Note that calling galleryList.Distinct() itself should compile (if you have the using directive) but it will just be comparing objects by reference as you haven't overridden Equals/GetHashCode.

If you actually need a collection of galleries, all of which have distinct categories, then you can use MoreLINQ which has a DistinctBy method:

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

In that case you'd need a using directive for the MoreLinq namespace.

You should also learn about automatically implemented properties. Your Gallery class can be written a lot more concisely as:

public class Gallery
{
    public string Category { get; set; }
}

people

See more on this question at Stackoverflow