如果没有值,则不创建键的字典

时间:2011-09-14 00:11:48

标签: linq linq-to-entities

我有两种类型UserArea

    public class User : IEntity
        {
            public int UserId { get; set; }
            public string Username { get; set; }
            public int AreaId { get; set; }
            public string CreatedByUserName { get; set; }
            public DateTime CreatedDateTime { get; set; }
            public string LastModifiedByUserName { get; set; }
            public DateTime? LastModifiedDateTime { get; set; }


        }

        public class Area : IEntity
            {
                public virtual int Id { get; set; }
                public virtual string Name { get; set; }
                public virtual int DefaultAdminId { get; set; }
                public string CreatedByUserName { get; set; }
                public DateTime CreatedDateTime { get; set; }
                public string LastModifiedByUserName { get; set; }
                public DateTime? LastModifiedDateTime { get; set; }

                //Navigation properties
                public virtual ICollection<User> Users { get; set; }
        }

Area可以包含一大堆Users。我想创建一个词典,其中Area名称是关键,每个键将包含UsersArea的关键值。

所以这是通过回答另一个问题来实现的:

var dictionary = Areas.ToDictionary(s => s.Name, s => s.Users.Where(c => c.AreaId == s.Id));

这很好,但是如果Area不包含任何Users,它仍然会被放入字典中,这不是我想要的。

有人可以告诉我如何省略不包含任何Areas的密钥Users吗?

2 个答案:

答案 0 :(得分:4)

您可以在将Areas发送到词典之前对其进行过滤。

var dictionary = Areas.Where(s => s.Users.Any()).ToDictionary...

答案 1 :(得分:0)

如果区域的用户与包含它们的AreaId不匹配,那就非常奇怪了:

   var usersByArea = (from area in areas
                      let areaUsers = area.Users.Where(u => u.AreaId == area.Id).ToList()
                      where areaUsers.Count > 0
                      select new
                      {
                          Name = area.Name,
                          Users = areaUsers
                      }).ToDictionary(a => a.Name, a => a.Users);