Reputation: 5039
I'm currently working (as a School Project) on a WebAPI for a conversation system. It's basically a mailbox between two users.
When adding a new message, I would like to check if two users have already talked to each others. Everything is currently stored as a variable in memory(it's only for school and can be improved later).
My model is something like this :
public class Conversation
{
public int Id { get; set; }
public int[] Users { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public List<Message> Messages { get; set; }
public static List<Conversation> listeConversation = new List<Conversation>
{
new Conversation {
Id = 1, Users = new int[2] {1, 2}, Messages = new List<Message> {
new Message { Id = 1, UserId = 1, Content = "Bonjour", Created = DateTime.Now},
new Message { Id = 2, UserId = 2, Content = "Comment ça va ?", Created = DateTime.Now},
new Message { Id = 3, UserId = 1, Content = "Très bien et toi ?", Created = DateTime.
}
};
}
In my method, I'm receiving sender and receiver id. I would like to create a new method where I check if the Conversation List already contains one conversation bewteen these two users, but I don't really know how to do it.
I suppose that I have to use Contains, but I don't really know how to use it with arrays. I tried something like this:
private Conversation getConversationFromUsers(int[] users)
{
Conversation.listeConversation.Where(c => c.Users.Contains(users));
}
But it's not working.
Upvotes: 0
Views: 302
Reputation: 1800
I would use HashSet<int>
to store the users whose conversations you want to find. This gives you access to the SetEquals()
method, which tests for set equality which is what you are looking for.
private Conversation getConversationFromUsers(int[] users)
{
var set = new HashSet<int>(users);
return Conversation.listeConversation.FirstOrDefault(c => users.SetEquals(c.Users));
}
Upvotes: 0
Reputation: 2086
Try using the LINQ Intersect()
method:
var foundConversations = Conversation.listeConversation.Where(c => c.Users.Intersect(users).Count() >= users.Lenght).ToList();
It should work with any length array of users.
Upvotes: 1
Reputation: 1800
If I understood your question correctly you need something like this?
Conversation.listeConversation.Where(c => c.Users.Contains(users[0]) && c => c.Users.Contains(users[1]);
Update: For more than two matches use something like this:
Conversation.listeConversation.Where(c => c.Users.Intersect(users).Count() > 2)
Upvotes: 2