Поделиться через


Linq Select Distinct Records based on a field or Property

Have a look at the sample below, Is there a simpler way of achieving this ? 

 

I needed the results

1 vp

2 x

3 y

Rest should be ignored

public class customer

        {

            public int id;

            public string name;

            public static IEnumerable<customer> getDistinct()

            {

                List<customer> cust = new List<customer>();

                cust.Add(new customer() { id = 1, name = "vp" });

                cust.Add(new customer() { id = 2, name = "x" });

                cust.Add(new customer() { id = 3, name = "y" });

                cust.Add(new customer() { id = 1, name = "vp" });

                cust.Add(new customer() { id = 1, name = "vfp" });

                cust.Add(new customer() { id = 1, name = "vp" });

                cust.Add(new customer() { id = 1, name = "vpd" });

                cust.Add(new customer() { id = 1, name = "vsp" });

                cust.Add(new customer() { id = 1, name = "vfrp" });

                IEnumerable<customer> newcust = cust.Distinct<customer>(new xcomp()) ;

             

                return newcust;

            }

            public class xcomp : IEqualityComparer<customer >

            {

                #region IEqualityComparer<customer> Members

                bool IEqualityComparer<customer>.Equals(customer x, customer y)

                {

                    return x.id == y.id;

                }

                int IEqualityComparer<customer>.GetHashCode(customer obj)

                {

                    return obj.id.GetHashCode();

                }

                #endregion

            }

        }