2

I have a list and i'm trying to remove all the duplicates from it using .Distinct() but i can't get it to work.

A simple class:

public class Street
{
    public string Name;
    public string Location;
}

Here i create a new instance and add to it:

List<Street> Streets = new List<Street>();

Streets.Add(new Street { Name = "Street1", Location = "District1" });
Streets.Add(new Street { Name = "Street1", Location = "District1" });
Streets.Add(new Street { Name = "Street2", Location = "District2" });

Create a distinct instance:

List<Street> DistinctStreets = Streets.Distinct().ToList();

Loop through the list:

foreach (Street street in DistinctStreets)
{
   HttpContext.Current.Response.Write("<p>" + street.Name + "</p>");
}

However, this returns

  • Street1

    Street1

    Street2

But i was expecting

  • Street1

    Street2

Can anyone explain what's going wrong and why my distinct instance isn't distinct?

thanks

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
Scott
  • 1,280
  • 4
  • 20
  • 35
  • 1
    Duplicate according to *what* criteria? `Distinct` depends on the `Equals` implementation of a class to detect whether two objects are equal. The default implementation of Object.Equals only compares object references, it doesn't try to compare an object's properties, fields etc. You need to define an `Equals` override that compares the properties you want to use for equality – Panagiotis Kanavos Jan 20 '16 at 11:20
  • 3
    You need to define **both** `Equals` & `GetHashCode` overrides. They work best on immutable classes. – Enigmativity Jan 20 '16 at 11:20
  • 1
    OR you can give `Distinct()` an `IEqualityComparer` (This question comes along about once every week. Why was the 'duplicate question' comment deleted?) – Dennis_E Jan 20 '16 at 11:23
  • Try this implementation of [Street](https://dotnetfiddle.net/g6jJoA). – Enigmativity Jan 20 '16 at 11:24
  • thanks all, i managed to get this working with @Enigmativity example and changing Add to: Streets.Add(new Street("Street1", "District1")); – Scott Jan 20 '16 at 11:35

0 Answers0