开发者

How to use Linq Contains()?

I am using nHibernate and I need to create a query that does this:

Course Table

CourseId
CourseName

Task Table // course can hav开发者_C百科e many tasks

TaskName
TaskId
CousreId

Now I need to do a contains:

 session
   .Query<Course>()
   .Where(x =>
     x.Tasks.Contains(/* wants a task object. I want to do it on property level. */) &&
     x.CourseId == 1)

How can I change my query to do a Contains on TaskName?


Project your Tasks to a TaskName then use contains on that.

var query = session
    .Query<Course>()
    .Where(x => x.Tasks
                 .Select(t => t.TaskName)
                 .Contains(myTaskName)
             && x.CourseId == 1);


If I correctly understood you can use Any method

session.Query<Course>().Where(x => x.Tasks.Any(t => t.Name == "task name")
                                               && x.CourseId == 1);


Have you tried this?

var results = session.Query<Course>()
      .Where(crs => crs.Tasks.Count(tsk => tsk.TaskName == theName) > 0);

This should count the number of tasks with the correct name (specified in theName in my example), and return all courses that have a count value greater than zero, i.e. all courses that contain a task with the specific name.


You either have to implement your own IComparer or IEqualityComparer (as I recall, I may be off) and base it on a specific property of the object. Or use Count() or Find() instead. Here's some pseudo code:

session.Query<Course>().Where(x => x.Tasks.Count(t => t.TaskProperty == "something") > 0 && x.CourseId == 1)


I would try something like this:

var results = session
    .Query<Course>()
    .Where(crs => crs.Tasks.Any(tsk => tsk.TaskName == theName) && crs.CourseId == 1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜