C# List 分组并通过Dictionary组装数据

以其中一个字段进行分组,并将分组的Key作为返回的键,分组后的列表作为值。代码如下:

	[HttpGet]
    public JsonResult GetAllUerList()
    {
        var userList = UserClient.GetAllUser();
        var ContactsList = new List();

        foreach (var item in userList)
        {
            var temp = new CurrentFirstLetterUserViewModel();
            temp.ID = item.ID;
            temp.ErpID = item.ErpID;
            temp.UserName = item.UserName;
            temp.FullName = item.FullName;
            temp.Email = item.Email;
            temp.DepartName = item.DepartName;
            var FullNameFirst = item.FullName.Substring(0, 1); // 姓
            var FirstLetter = PinYinConverter.GetFirst(FullNameFirst); // 姓对应的首字母
            temp.FirstLetter = FirstLetter;
            ContactsList.Add(temp);
        }

        var dict = ContactsList.OrderBy(s => s.FirstLetter).GroupBy(s => s.FirstLetter).Select(group => {
            var dic = new Dictionary();
            dic.Add("firstLetter", group.Key);
            dic.Add("itemList", group.ToList());
            return dic;
        });

        return Json(new { data = dict, success = true }, JsonRequestBehavior.AllowGet);
    }

你可能感兴趣的:(C#)