我有这个C#代码
var items = new Dictionary<string, DateTime>()
{
{ "1", new DateTime(2018, 12, 12) }, // year, month, day
{ "2", new DateTime(2018, 12, 10) },
{ "4", new DateTime(2017, 12, 12) },
{ "3", new DateTime(2018, 10, 12) }
};
var groupedItems = items.GroupBy(i => new
{
i.Value.Year,
i.Value.Month
});
Console.WriteLine(groupedItems);
哪个在LINQPad中给了我
我想对它进行排序和排序以获取此信息:
var items = new Dictionary<string, List<string>>()
{
{
"2018/12", new List<string>()
{
"1",
"2"
}
},
{
"2018/10", new List<string>()
{
"3",
}
},
{
"2017/12", new List<string>()
{
"4",
}
}
};
我该怎么做?
我尝试使用更多的GroupBy
,但实际上并不能实现我想要的功能,我想我对逻辑太不好了
答案 0 :(得分:4)
根据您的示例,您的意思是这样的吗:
var groupedItems = items
.OrderByDescending(item => item.Value)
.GroupBy(i => new
{
i.Value.Year,
i.Value.Month
})
.ToDictionary
(
group => $"{group.Key.Year}/{group.Key.Month}",
group => group.Select(item => item.Key).ToList()
);
这是Dictionary<string, List<string>>
,其中Key
是year/month
,值是一年中该月内的字符串值列表。