Monday, January 23, 2012

LINQ - Distinct using IEqualityComparer

Step 1 :Create Generic class.

 
public class MatType : IEquatable<MatType>
 {
        public int MatTypeId { get; set; }

        public string MatTypeName { get; set; }

       public string MatColor { get; set; }
 }


Step 2 : Bind Collection to class.

  private List<MatType> _matTypes;
        public List<MatType> MatTypes
        {
            get ;
            set ;
        }

MatTypes = new List<MatType>();

 // add some data into it

MatTypes.Add (new  MatType() {......//here are data});
 
Step 3 : Create Comparer to return result distinct by MatTypeId.
 
 public class MatTypeComparer : IEqualityComparer<MatType>
        {
            public bool Equals(MatType x, MatType y)
            {
                return (x.MatTypeId == y.MatTypeId);
            }
            public int GetHashCode(MatType x)
            {
                return (x.MatTypeId.GetHashCode());
            }
        }

Step 4: Use MatTypeComparer to get distinct result.

 MatTypes = new List<MatType>(mats.Select(x => x.Type).Distinct(new MatTypeComparer()).ToList());

No comments:

Post a Comment