views:

1624

answers:

4

I have a class Items with properties (Id, Name, Code, Price).

The List of Items is populated with duplicated items.

For ex.:

1         Item1       IT00001        $100
2         Item2       IT00002        $200
3         Item3       IT00003        $150
1         Item1       IT00001        $100
3         Item3       IT00003        $150

How to remove the duplicates in the list using linq?

+18  A: 
var distinctItems = items.Distinct();

To match on only some of the properties, create a custom equality comparer, e.g.:

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id &&
            x.Name == y.Name &&
            x.Code == y.Code &&
            x.Price == y.Price;
    }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode() ^
            obj.Code.GetHashCode() ^
            obj.Price.GetHashCode();
    }
}

Then use it like this:

var distinctItems = items.Distinct(new DistinctItemComparer());
Christian Hayter
i tried this, but not removing duplicates
Prasad
Updated with your second requirement.
Christian Hayter
Hi Christian , What will be the change in code if i have a List<my_Custom_Class> and List<string>. My custom class has various items in which one is DCN number and list<string> has only DCN number. So I need to check the List<Custom_Class> contains any dcn from List<string>. For example suppose List1 = List<Custom_Class> and List2 = List<String>. If List1 has 2000 items and list2 has 40000 items on which 600 items from List1 exists in List2. So in this case i need 1400 as my output List as list1. So what would be the expression. Thanks in advance
Amit Ranjan
Also one more case is here since List1 contains various items , other items values might be different but the DCN must be same. So in my case Distinct failed to give desired out put.
Amit Ranjan
+6  A: 

Use Distinct() but keep in mind that it uses the default equality comparer to compare values, so if you want anything beyond that you need to implement your own comparer.

Please see http://msdn.microsoft.com/en-us/library/bb348436.aspx for an example.

Brian Rasmussen
+4  A: 

If there is something that is throwing off your Distinct query, you might want to look at MoreLinq and use the DistinctBy operator and select distinct objects by id.

var distinct = items.DistinctBy( i => i.Id );
tvanfosson