Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading