Thursday, May 10, 2012

Creating Comparer in C# to Get Distinct values from Generic Collection

First Create class


  public class GlassType
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
    } 

Now Create one comparer custom class to check for distinct value by ID

 public class UserComparer : IEqualityComparer<GlassType>
 {
      public bool Equals(GlassType x, GlassType y)
      {
         return (x.Id == y.Id);
      }
      public int GetHashCode(GlassType x)
      {
         return (x.Id.GetHashCode());
      }
 }


In above colde i have created custom class that filters distinct values from generic collection.


Then Create one property in your class that has collections of GlassType

private ObservableCollection<GlassType> glassTypeList;
public ObservableCollection<GlassType> GlassTypeList
{
   get { return glassTypeList; }
   set
   {
       if (glassTypeList != value)
       {
          glassTypeList = value;
          RaisePropertyChanged(() => GlassTypeList);
       }
   }
}

Using UserComparer get Distinct values.

var Result; //Result contains list of GalssType retrive from service

 GlassTypeList = new ObservableCollection<GlassType>
       (Result.Select(x => x.GlassType).Distinct(new UserComparer()).ToList()); 

No comments:

Post a Comment