简体   繁体   English

在 Lambda 中使用包含 IQueryable object 和匿名字段

[英]Using Contains in Lambda with a IQueryable object and a Anonymous field

So after reading several post about how to use Contains in Lambda I can't seem to get this to work.因此,在阅读了几篇关于如何在Lambda中使用Contains的帖子后,我似乎无法让它工作。 It should be straightforward but I am struggling big time with this up to the point where I am about to just rewrite it in Dapper.它应该很简单,但我一直在努力解决这个问题,直到我即将用 Dapper 重写它。

The problem is as follow: I have a data object (build with EntityFramework ) which retrieves some data from the database, this data is being saved in a variable of type IQueryable<a> :问题如下:我有一个数据 object (使用EntityFramework构建)从数据库中检索一些数据,这些数据保存在IQueryable<a>类型的变量中:

var data = raw.Select(p => new 
    {
        Id = p.Id,
        StatusId = p.StatusId,
        ProjectName = p.Room.Department.Project.Name,
        ProjectId = p.Room.Department.Project.Id,
        DepartmentName = p.Room.Department.Name,
        DateCreated = p.DateCreated,
        RoomName = p.Room.Name,
        UserCreatedName = p.UserCreated.Firstname + (string.IsNullOrEmpty(p.UserCreated.Insertion) ? string.Empty : " ") + p.UserCreated.Insertion + " " + p.UserCreated.Lastname,
        Comment = p.Comment,
    });

In some circumstances I need to filter the data, this filter is a list of certain project Id's:在某些情况下,我需要过滤数据,此过滤器是某些项目 ID 的list

List<Right> rights = Rights.GetItems(userId).ToList();
var projectIds = rights.Select(x => x.ItemId);

The data object should only return records which match the id's of the projectIds list .数据 object 应该只返回与projectIds list的 id 匹配的记录。

Though for some reason I can't do this:虽然由于某种原因我不能这样做:

data = data.Where(p => x.ProjectId.Contains(projectIds);

The ProjectId field does not have a Contains overload, is this because it is a Anonymous type ? ProjectId字段没有Contains重载,这是因为它是Anonymous type吗?

I am working in an MVC 5 project ( .NET 4.7 ).我正在从事MVC 5项目( .NET 4.7 )。

I would suspect you want to check your projectsIds list contains the project id, instead of trying to see if the projectId contains your list of project ids?我怀疑您想检查您的 projectsIds 列表是否包含项目 ID,而不是尝试查看 projectId 是否包含您的项目 ID 列表?

So try this?所以试试这个?

data = data.Where(p => projectIds.Contains(p.ProjectId));

The projectId is most likely int, string or guid? projectId 最有可能是 int、string 还是 guid? the Contains method is an extension method for type generic IEnumerable. Contains 方法是泛型 IEnumerable 类型的扩展方法。 The ProjectId is most likely not an IEnumerable and therefore it does not have the overload. ProjectId 很可能不是 IEnumerable,因此它没有重载。 Contains 包含

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM