代码:
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"
}
]
}
网友评论