Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have a list that 4 objects with three fields has the following
The fields are string day, int Id and string time
[0] Sunday  1    9:00 to 10:00
[1] Monday  1    9:00 to 10:00
[2] Sunday  1    9:00 to 10:00
[3] Monday  1    9:00 to 10:00


I don't want the output to have repeated values, so the output should be like this

[0] Sunday  1    9:00 to 10:00
[1] Monday  1    9:00 to 10:00


What I have tried:

I tried list.Distinct(); but it's output remained the same.
Posted
Updated 12-May-20 7:06am
v3
Comments
MadMyche 12-May-20 10:29am    
Please use the Improve Question widget and add in the Class definition for the object in question
Member 14800672 12-May-20 11:03am    
I added the fields types in the question
String Day; example: Sunday
Int id; example: 1
String time; example: 9:00 to 10:00

Your object needs to implement IEquatable<T>:
IEquatable<T> Interface (System) | Microsoft Docs[^]

Or you need to provide a custom IEqualityComparer<T> to the Distinct method:
IEqualityComparer<T> Interface (System.Collections.Generic) | Microsoft Docs[^]
 
Share this answer
 
Comments
Maciej Los 12-May-20 11:44am    
5ed!
Another way (as an alternative to solution #1) is to use GroupBy + Select

C#
var distinctValues = listofvalues
    .GroupBy(x => new {Day = x.Day, Id = x.Id, Time = x.Time})
    .Select(grp => grp.First())
    .ToList();


Shorter version of above:
C#
var distinctValues = listofvalues
    .GroupBy(x => new {Day = x.Day, Id = x.Id, Time = x.Time}, (key, x) => x.FirstOrDefault())
    .ToList();


or use ToLookup()[^]
C#
var distincts = listofvalues
		.ToLookup(c => new {Day = x.Day, Id = x.Id, Time = x.Time})
		.Select(g => g.First())
		.ToList();
 
Share this answer
 
v2
Comments
George Swan 13-May-20 2:48am    
A great answer. You can make your shorter version even shorter by using a Tuple instead of an anonymous type as they both use the default equality comparer for each property.
.GroupBy(x => (x.Day, x.Id, x.Time),(k,x)=>x.FirstOrDefault())
Maciej Los 13-May-20 2:51am    
Thank you, George.
Using Tuple is great idea!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900