使用LINQ?</objectid>>在Dictionary <objectid,class =“”>中查询值

时间:2012-11-29 20:59:09

标签: c# .net linq mongodb mongodb-.net-driver

考虑下面的学生和教师的简单例子;

// person
public class Person
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public Person() {
        Id = ObjectId.GenerateNewId(DateTime.Now);
    }
}

// student has a Classroom
public class Student : Person
{
    public string Classroom { get; set; }
}

// teacher has a Dictionary<ObjectId, Student> Students
public class Teacher : Person
{
    [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)]
    public Dictionary<ObjectId, Student> Students { get; set; }
    public Teacher() {
        Students = new Dictionary<ObjectId, Student>();
    }
}

class Program
{
    static void Main(string[] args)
    {

        var server = MongoServer.Create("mongodb://localhost/database?safe=true");
        var database = server.GetDatabase("sandbox");
        var collection = database.GetCollection<Teacher>("teachers");
        collection.Drop();

        // create students
        var s1 = new Student() { Name = "s1", Classroom = "foo" };
        var s2 = new Student() { Name = "s2", Classroom = "foo" };
        var s3 = new Student() { Name = "s3", Classroom = "baz" };
        var s4 = new Student() { Name = "s4", Classroom = "foo" };

        // teacher 1
        var t1 = new Teacher() { Name = "t1" };
        t1.Students.Add(s1.Id, s1);
        t1.Students.Add(s2.Id, s2);
        collection.Insert(t1);

        // teacher 2
        var t2 = new Teacher {Name = "t2"};
        t2.Students.Add(s3.Id, s3);
        collection.Insert(t2);

        // add teacher 3 
        var t3 = new Teacher() {Name = "t3"};
        t3.Students.Add(s4.Id, s4);
        collection.Insert(t3);

        // select via key
        var onlyt1 = collection.AsQueryable().Where(t => t.Students.ContainsKey(s1.Id)).ToList();

        Console.WriteLine("onlyt1 : {0}", onlyt1.ToJson());
        Console.ReadLine();
    }
}

我可以通过键选择(如上所示),但是如何找到所有拥有“foo”课堂学生的老师?我想写一些像;

// select via value
var shouldBeJustT1andT3 = collection.AsQueryable().Where(t => t.Students.Values.Where(s => s.Classroom == "foo")).ToList(); 

2 个答案:

答案 0 :(得分:2)

您可以使用任何来获得任何教师,在给定教室中有学生“foo”:

List<Teacher> shouldBeJustT1andT3 = collection.Where(
    teacher => teacher.Students.Any(student => student.Classroom == "foo")
).ToList(); 

修改

由于Mongo的IQueryable默认情况下不支持 Any ,您可以使用WhereCount代替Any

List<Teacher> shouldBeJustT1andT3 = collection.Where(
    teacher => teacher.Students.Where(student => student.Classroom == "foo").Count() > 0
).ToList(); 

答案 1 :(得分:0)

你不能只有Students类型的ICollection<Person>吗?

然后您不需要查询字典的值,而是需要平面对象的列表,即where s.ID == x && s.Classroom == "blah"

字典只能按键查找对象,即t.Students[studentId]


找老师:看到dbaseman的答案,他是对的。