Mongodb, linq driver. How to construct Contains with variable or statements

心不动则不痛 提交于 2019-12-19 07:52:21

问题


I'm using the Mongo LINQ Driver for C#, works great.

Sorting a lot of properties but heres a problem I can't solve, its probably simple.

var identifierList = new []{"10", "20", "30"};
var newList = list.Where(x => identifierList.Contains(x.Identifier));

This is NOT supported ... 

So I could do something like:

 var newList = list.Where(x => x.Identifier == "10" || x.Identifier == "20" || x.Identifier == "30");

But since the list is variable ... how do I construct the above? Or are there even better alternatives?

The list is of type IQueryable<MyCustomClass>

For information ... this is used as a filter of alot of properties. In SQL I could have a parent -> child relationship. But as I can't as the parent for the main ID I need to take all the ID's out and then construct it like this.

Hopes this makes sense. If needed I will explain more.


回答1:


To answer my own question ... The Mongo Sharp LINQ driver has an extension method called "In" which does exactly what I need.

They have however implemented it in 1.5 so we can use the old way like: https://jira.mongodb.org/browse/CSHARP-462

 var list = new []{"10", "10"};

 search.Where(x => list.Contains(x.Id));

But the version 1.5 package is not on nuget yet.

However, this should work with the "In" extension that comes as a special surprise with the mongo-csharp-driver.

 search.Where(x => x.In(list));



回答2:


var identifierList = new []{"10", "20", "30"};
var newList = list.ToList().Where(x => identifierList.Contains(x.Identifier));

You will just have to use List instead of Ienumerable (do that by using the .ToList())

If it doesn't work please add your list TYPE



来源:https://stackoverflow.com/questions/10922998/mongodb-linq-driver-how-to-construct-contains-with-variable-or-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!