Skip to content
Advertisement

LINQ Room id where user exists

I have two tables:

ChatRoom

  • Id (int)

ChatUser (where i insert the users to the chat room, 1 row per user)

  • RoomId (int) // Id from table ChatRoom
  • UserId (int)

I want to loop out all rooms where im in i do like this.

ChatUserDTO chatUser = db.ChatUser.Where(x => x.UserId == userId);

But how do get the room id where the second user with the variable userId2 exists? If there are no rooms where both user exists it should return RoomId = 0.

Got it to work with this code but there must be a better way to do it.

var chatExists = (from cu in db.ChatUser
                 where cu.UserId == userId    
                 select new { cu.RoomId })
                 .ToList();

var chatRoomId = 0;

foreach (var item in chatExists)
{
    ChatUserDTO checkRoom = 
            db.ChatUser.FirstOrDefault(
                x => x.UserId == userId2 && x.RoomId == item.RoomId);

    if (checkRoom != null)
        chatRoomId = checkRoom.RoomId;
}

Advertisement

Answer

You could intersect the two sets of rooms, this gives you more information than you requested:

var rooms1 = db.ChatUser.Where(cu => cu.UserId == userId).Select(cu => cu.RoomId);
var rooms2 = db.ChatUser.Where(cu => cu.UserId == userId2).Select(cu => cu.RoomId);

var roomsWithBoth = rooms1.Intersect(rooms2);

Another alternative would be to use GroupBy to group the ChatUser records by room and then find rooms that contain both userIds. This approach might be better if, say, you have N different users and are looking for a common room.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement