I have a program where there is a topic (like a forum), people can react to that topic.
USER:
TOPIC:
REACTION:
Code:
List<USER> ListOfAllUsers = new List<USER>();
var AllReactions = from r in db.REACTIONs
where r.topic_id == _topic_id
select r;
foreach (var itemX in AllReactions)
{
ListOfAllUsers.Add(itemX.USER);
}
//Distinct the list of duplicates
var ListOfUsers = ListOfAllUsers.Distinct().ToList();
Now, the "distinct" list still has some duplicates, how do I distinct the list based on the user id's? Or maybe there is another better way to do this. Thanks in advance.
C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).
Yes, it doesn't work as expected! This is because the Distinct method uses the default equality comparer to compare the values under the hood. Since we are dealing with reference type object, the Distinct() method will treat the values as unique even if the property values are the same.
Returns a list that contains all the values in list list with duplicates removed. If the list is empty, the result is an empty list.
You can use GroupBy to achieve that
var ListOfUsers = ListOfAllUsers.GroupBy(x => x.Id)
.Select(g => g.First())
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With