开发者

Dictionary which doesn't create key if there are no values

开发者 https://www.devze.com 2023-04-04 12:13 出处:网络
I have two types User and Area. public class User : IEntity { public int UserId { get; set; } public string Username { get; set; }

I have two types User and Area.

    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 can contain a whole bunch of Users. I was wanting to create a Dictionary where the Area name is the key and each key will contain the Users in this Area for the values of the key.

So this was achieved in an answer to another one of my questions using:

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

This is great but if the Area doesn't contain any Users it is still put in开发者_高级运维to the dictionary which is not what I want.

Could someone please give me some idea on how I would leave out the keys Areas which don't contain any Users?


You can filter Areas before sending it to the dictionary.

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


It is very strange for areas to have users wich do not match the AreaId that contains them but nevertheless:

   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);
0

精彩评论

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