Search code examples
c#linqmongodb-.net-driver

Problem using "Any" method inside "Where" method in Linq MongodbDriver


I'm new in using linq and having some problem . I've got a big collection of type A and a small collection of type B. I want the list of items in A which their "id" does exist in B. So here is what I did think could work:

List<string> list = collection_A
                .Where(c => collection_B.Any(x => x.MessageId == c.Id))
                .Select(c=>c.Id)
                .ToList();

I'm using mongoDB linq provider in .Net and the error is : System.ArgumentException: Unsupported filter. The relation is 1-1

Actually I don't know if I should use "Join" in this case or something else.


Solution

  • I'd suggest that you try this:

    var messageIds = new HashSet<string>(collection_B.Select(x => x.MessageId).Distinct());
    
    List<string> list =
        collection_A
            .Where(c => messageIds.Contains(c.Id))
            .Select(c => c.Id)
            .ToList();