我有一个类似于以下内容的List<Dictionary<string, object>>:
var myList =
new List<Dictionary<string, object>>
{
new Dictionary<string, object>
{
{ "Name", "Bob" },
{ "Certification", "Certification A" },
{ "Date", "10/1/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Bob" },
{ "Certification", "Certification A" },
{ "Date", "01/01/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Bob" },
{ "Certification", "Certification B" },
{ "Date", "10/5/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Joe" },
{ "Certification", "Certification A" },
{ "Date", "10/5/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Joe" },
{ "Certification", "Certification B" },
{ "Date", "10/5/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Joe" },
{ "Certification", "Certification B" },
{ "Date", "01/01/2022" }
}
};我需要按Name和Certification进行分组,这样我就可以得到以下结果:
{
new Dictionary<string, object>
{
{ "Name", "Bob" },
{ "Certification", "Certification A" },
{ "Date", "10/1/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Bob" },
{ "Certification", "Certification B" },
{ "Date", "10/5/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Joe" },
{ "Certification", "Certification A" },
{ "Date", "10/5/2022" }
},
new Dictionary<string, object>
{
{ "Name", "Joe" },
{ "Certification", "Certification B" },
{ "Date", "10/5/2022" }
}
};我完全不知道如何达到这个结果,所以任何的指导都会很感激。
发布于 2022-10-12 23:19:56
您可以使用它们生成的相等成员来利用值元组:
var result = myList.GroupBy(d => (Name: d["Name"], Certification: d["Certification"]))
.Select(g => g.First()) // apply ordering if needed
.ToList();或者匿名类型也是如此:
var result = myList.GroupBy(d => new { Name = d["Name"], Certification = d["Certification"] })
.Select(g => g.First()) // apply ordering if needed
.ToList();请注意,这将要求所有字典都有所有成员和所有值,以正确实现Equals和GetHashcode。
还要注意,您可以将字典键入为Dictionary<string, string>。
https://stackoverflow.com/questions/74048869
复制相似问题