开发者

Create new Dictionary<string, IEnumerable<SelectListItem> type using IDictionary

Hi I have a list of users. Each User belongs to an Area.

What I'm wanting to do with this list is create a dictionary from them where the Area Name is the Key and the value for the key is a selectList of Users in the Area the with a Text value of the Username and a Value set to the User Id.

I managed to achieve this using the following code:

    var StaffByArea = new Dictionary<string, IEnumerable<SelectListItem>>();

    foreach(var area in areas)) {
                        var personList = new List<SelectListItem>();
                        foreach (var person in staff.Where(c => c.AreaId == area.Id)) {
                            personList.Add(new SelectLis

tItem { Value = person.AreaId.ToString(), Text = person.Username });
                    }

                    StaffByArea.Add(area.Name, personList);
            }

So for every possible area I'm finding correlating staff and adding them to a selectlist. Once I've added all the people for the area I add that select list to the dictionary with the area name as key.

I've been thinking this maybe ea开发者_Python百科sier to do with ToDictionary()

Does anyone know how to do this?

I've only got as far as:

StaffByArea = Users.ToDictionary(x => x.Area.Name, ...);


Try this:

var StaffByArea
    = areas.ToDictionary(
        a => a.Name,
        a => staff
                .Where(c => c.AreaId == area.Id)
                .Select(c => new SelectListItem 
                { 
                    Value = c.AreaId.ToString(), 
                    Text = c.Username 
                }));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜