美文网首页
C# 根据英文首字母排序

C# 根据英文首字母排序

作者: Rinaloving | 来源:发表于2020-11-17 11:31 被阅读0次

    代码:

    List<string> list = new List<string>() { "Ace", "Abbiy", "Jack", "Rose", "Micheal", "Milk", "Lucy", "Peach", "Jimmy" };
    Dictionary<string, dynamic> dict = new Dictionary<string, dynamic>();
    List<IGrouping<string, string>> data = list.OrderBy(p => p.Substring(0, 1)).GroupBy(p => p.Substring(0, 1)).ToList();
    
    foreach (var item in data)
     {
          dict.Add(item.Key, item.Select(p => new {  Name = p }));
     }
    Console.WriteLine(JsonConvert.SerializeObject(dict));
    

    结果:

    {
        "A":[
            {
                "Name":"Ace"
            },
            {
                "Name":"Abbiy"
            }
        ],
        "J":[
            {
                "Name":"Jack"
            },
            {
                "Name":"Jimmy"
            }
        ],
        "L":[
            {
                "Name":"Lucy"
            }
        ],
        "M":[
            {
                "Name":"Micheal"
            },
            {
                "Name":"Milk"
            }
        ],
        "P":[
            {
                "Name":"Peach"
            }
        ],
        "R":[
            {
                "Name":"Rose"
            }
        ]
    }
    

    相关文章

      网友评论

          本文标题:C# 根据英文首字母排序

          本文链接:https://www.haomeiwen.com/subject/arrxiktx.html