Reputation: 1596
I have a List<Dictionary<string, object>>
that looks similar to the following:
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" }
}
};
I am needing to group by Name
and Certification
so that I end up with:
{
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" }
}
};
I'm completely stumped on how to get to that result so any guidance would be appreciated.
Upvotes: 0
Views: 343
Reputation: 142843
You can just leverage the value tuples with their generated equality members:
var result = myList.GroupBy(d => (Name: d["Name"], Certification: d["Certification"]))
.Select(g => g.First()) // apply ordering if needed
.ToList();
Or the same with anonymous types:
var result = myList.GroupBy(d => new { Name = d["Name"], Certification = d["Certification"] })
.Select(g => g.First()) // apply ordering if needed
.ToList();
Note that this will require all dictionaries to have all members present and all values to correctly implement Equals
and GetHashcode
.
Also note that you can type your dictionaries as Dictionary<string, string>
Upvotes: 2