Tuesday, September 14, 2010

Using LINQ to get a Distinct List

First, create a type comparer:

    public class ItemComparer : IEqualityComparer<Item>
    {
        #region IEqualityComparer<Item> Members
 
        public bool Equals(Item x, Item y)
        {
            return x.ItemID == y.ItemID;
        }
 
        public int GetHashCode(Item obj)
        {
            return obj.ItemID.GetHashCode();
        }
        #endregion
    } 


Then, use it as follows on a List items:

    IEnumerable<Item> distinctItems = 
          items.Distinct(new ItemComparer());
    items = distinctItems.ToList();

No comments:

Post a Comment