Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct a list with objects by id

I have a program where there is a topic (like a forum), people can react to that topic.

USER:

  1. id
  2. first name
  3. last name

TOPIC:

  1. id
  2. subject

REACTION:

  1. id
  2. topic_id
  3. content

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.

like image 543
Niek Jonkman Avatar asked Dec 18 '13 10:12

Niek Jonkman


People also ask

What is distinct () in C#?

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).

Why distinct is not working in Linq?

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.

What is distinct list?

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.


1 Answers

You can use GroupBy to achieve that

var ListOfUsers = ListOfAllUsers.GroupBy(x => x.Id)
                                  .Select(g => g.First())
                                  .ToList();
like image 136
Kamil Budziewski Avatar answered Oct 06 '22 19:10

Kamil Budziewski