-5

So in the controller, I accept a list of objects as follows:

    public virtual ActionResult Grid_Read([DataSourceRequest]DataSourceRequest request, IEnumerable<ObjDTO> objects)
    {
         var DistinctList = objects.Distinct();

         return Json(DistinctList.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
    }

But the .Distinct() does nothing to the list.

GeorgeB
  • 808
  • 1
  • 8
  • 26
  • Please search before you take the time to post stuff like this. This has been asked several times before and there are already good answers on this topic – Camilo Terevinto Mar 20 '18 at 17:36

1 Answers1

-3

So to fix this you will need to navigate to the DTO that is being used as the type, in this case 'ObjDTO'. You will need to create a custom equality comparer.

I used the following code to make this comparer:

public string Item1 {get;set;}
public int Item2 {get;set;}

public override bool Equals(object obj)
{
    var item = obj as ObjDTO;

    if (item == null)
    {
        return false;
    }

    return this.Item1 == item.Item1 && this.Item2 == item.Item2;
}

public override int GetHashCode()
{
    if (this.Item1 == null && this.Item2 == 0)
    {
        return base.GetHashCode();
    }

    return this.Item1.GetHashCode() + this.Item2.GetHashCode();
}

So, the reason distinct was not working is because each object in that DTO being accepted had a unique hashcode, this is invisible. So with that in mind, our custom comparer, does the job of comparing the values within the object, then combines the hashcodes and returns.

And that gives us a list of distinct values with unique hashcodes.

GeorgeB
  • 808
  • 1
  • 8
  • 26
  • 1
    It is usually welcomed to post self-answered question if you solved a problem of yours and want tho share the knowledge. But all other SO rules still apply. With a little search you could have found the thousands of duplicates of this kind of question. – René Vogt Mar 20 '18 at 17:36
  • 1
    Your hash is invalid. The hash uses the object reference as the identity when the items are null and zero, but the equals operator considers two items with those values equal to each other. – Servy Mar 20 '18 at 17:47
  • "with unique hashcodes"? hash codes aren't unique, that's not how it works. If two items have different hash codes, `Distinct` knows that they aren't equal without needing to call `Equals`. But if they have the same hash code, `Equals` must be called to determine if they are equal.or not. Thatswhy it's absolutely necessary that if `Equals` returns `true` for two items, then `GetHashCode` returns _equal_ hashes for these items. But that's not what your code does (as Servy's comment describes). – René Vogt Mar 21 '18 at 11:47