Distinct a list with objects by id

Viewed 20318

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.

5 Answers

I tried in .Net core similar code. No need to define explicit comparator. Override Equals and GetHashcode in class. No need to GroupBy. By default Distinct() works even if other props are distinct.

public class User  
    {
        public int Id { get; set; }    
        public string FirstName { get; set; }            
        public string LastName { get; set; }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj)) return true;    
            if (obj is User && (obj as User).Id == this.Id) return true;    
            return false;          
        }

        public override int GetHashCode()
        {
            int hashProductCode = Id.GetHashCode();    
            return hashProductCode;
        }    
    }

User[] users =  {
                new User {Id=1, FirstName="John", LastName="Smith" },
                new User {Id=2, FirstName="Mary", LastName="Blood" },
                new User {Id=1, FirstName="Sergey", LastName="Ivanov" }
            };

            var usersDistinct = users.Distinct().ToArray();
            Console.WriteLine(usersDistinct.Count()); //2 =John + Mary
Related