Home > other >  Exclude duplicate pair from List<model, model>
Exclude duplicate pair from List<model, model>

Time:11-05

In result of my select

var names = _db.Messages
            .Where(p => p.UserId == parameters.UserId || p.ToUserId == parameters.UserId)
                    .Select(p => new {p.FirstUser, p.SecondUser})
            .Distinct()
            .ToList();

I get four elements of type List<User, User>.

select

As you can see I have one duplicates

[0] and [2]. Only in sequence FirstUser and SecondUser they have difference

How can I Exclude one of them in query before ToList() ? And it will be perfect if in result I will have List<User> with all of them without duplicates.

CodePudding user response:

Looks that you don't care about who send the message and who received it. This is a solution for you:

var names = 
   _db.Messages
   .Where(p => p.UserId == parameters.UserId || p.ToUserId == parameters.UserId)
   .Select(p => new {
          user1 = p.UserId > p.ToUserId ? p.FirstUser.Id : p.SecondUser.Id,
          user2 = p.UserId <= p.ToUserId ? p.FirstUser.Id : p.SecondUser.Id,
          })
   .Distinct()
   .ToList();
  • Related