I have a list of objects from a class called ScrewBoltPattern.
I want to create a dictionary which contains the number of appearances of each family of ScrewBoltPattern. To decide if a screw belongs to a family I use some properties of that class.
To simplify this query let's say I use the properties Length and Diameter.
I want to create a Dictionary which has keys formatted like screw.Length + "_" + screw.Diameter
How can I get this?
This is what I've done so far
Dictionary<string, int> boltFamilyList = selectedBolts
.GroupBy(bolt => new { bolt.Length, bolt.Diameter })
.ToDictionary(bolt => bolt.Key, bolt => bolt.Count());
I need to give format to the dictionary key somewhere, but I don't know how to do it.
You can format the key in the group by:
Dictionary<string, int> boltFamilyList = selectedBolts
.GroupBy(bolt => $"{bolt.Length}_{bolt.Diameter}")
.ToDictionary(bolt => bolt.Key, bolt => bolt.Count());
Your group key (and by proxy your dictionary key) will be that formatted string.
Try it online
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With