在 Linq Mongodb 驱动程序的 "Where" 方法中使用 "Any" 方法的问题

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

我是 linq 的新手,遇到了一些问题。我有一个大的 A 型集合和一个小的 B 型集合。 我想要 A 中的项目列表,它们的 "id" 确实存在于 B 中。 所以这是我认为可行的方法:

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

我在 .Net 中使用 mongoDB linq 提供程序,错误是:System.ArgumentException:不支持的过滤器。关系是 1-1

实际上我不知道我应该在这种情况下使用 "Join" 还是其他。

我建议你试试这个:

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();

如果我正确理解了您的问题,以下代码将为您指明正确的方向。 我使用 MongoDAL 进行数据访问,这只是围绕 c# 驱动程序的抽象。

using System;
using System.Linq;
using MongoDAL;

namespace Example
{
    class Person : Entity
    {
        public string Name { get; set; }
    }

    class BanRecord : Entity
    {
        public One<Person> Person { get; set; }
        public string ReasonForBan { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new DB("testdatabase");

            var person1 = new Person { Name = "Person One" };
            var person2 = new Person { Name = "Person Two" };
            var person3 = new Person { Name = "Person Three" };

            person1.Save();
            person2.Save();
            person3.Save();

            var ban1 = new BanRecord
            {
                Person = person1.ToReference(),
                ReasonForBan = "Cause we can!"
            };
            ban1.Save();

            var ban2 = new BanRecord
            {
                Person = person2.ToReference(),
                ReasonForBan = "Cause we can!"
            };
            ban2.Save();

            var bannedPeople = (from b in DB.Collection<BanRecord>()
                                join p in DB.Collection<Person>() on b.Person.ID equals p.ID into banned
                                from p in banned
                                select p).ToArray();

            Console.ReadKey();
        }
    }
}