c#将列表映射到ILookup <int,tenant>

时间:2018-07-10 10:51:03

标签: c# linq linq-to-entities

基于以下类别。

    public class User
    {
        public int Id { get; set; }
        public List<TenantUser> TenantUsers { get; set; }
    }


    public class TenantUsers
    {
        public int UserId { get; set; }
        public User User { get; set; }
        public int TenantId { get; set; }
        public Tenant Tenant { get; set; }
    }

    public class Tenant
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<TenantUser> TenantUsers { get; set; }
    }

我正在尝试生成一个linq查询,该查询将返回一个Lookup<int,Tenant>() int是TenantUsers的userId。

到目前为止我的尝试:

var userIds = new int[] {1, 2,3,5};
var tenantUsers = new List<TenantsUsers>();

var tenants = 
tenantUsers
.Where(m => userIds.Contains(m.UserId))
.ToLookup(x=>x.UserId); 

以上是我走了多远。这将返回ILookup<int,TenantUsers>我正在寻找ILookup<int,Tenant>();

1 个答案:

答案 0 :(得分:1)

您必须从这样的结果中选择Tenant

var userIds = new int[] {1, 2,3,5};
var tenantUsers = new List<TenantsUsers>();

var tenants = 
tenantUsers
.Where(m => userIds.Contains(m.UserId))
.ToLookup(x => x.UserId, y => y.Tenant); 

C# Fiddle