[SOLVED] Return only unique(distinct) element based on certain properties from an array

Issue

I am looking for a way to return only distinct elements in an array but that has to be based on a certain property, other properties of the array can be duplicated.
eg:

var elements = [{id:123,name:"abc",start:12:00:00},{id:123,name:"abc",start:12:00:00},
{id:123,name:"abc",start:1:00:00},{id:123,name:"def",start:12:00:00}]

we only want to return results based on unique start time and name as :

[{id:123,name:"abc",start:12:00:00},{id:123,name:"abc",start:1:00:00},{id:123,name:"def",start:12:00:00}]

the property either name or start has to be different for each element {id:123,name:"abc",start:12:00:00} => is returned only once as there is two elements with the same name and start.

I looked for DistinctBy functionality but it does not allow me to use the function. Only has Distinct() function.

Solution

The easy way to do this is with a GroupBy, so if you want to have a unique name or start you could do it like this:

var elements = [
    {id:123,name:"abc",start:12:00:00},
    {id:123,name:"abc",start:12:00:00},
    {id:123,name:"abc",start:1:00:00},
    {id:123,name:"def",start:12:00:00}
];
var unique = elements
    .GroupBy(e => new {e.name, e.start})
    .Select(g => g.First())
    .ToArray(); // or ToList, or just leave it as an IEnumerable

Answered By – Turksarama

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *