Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ group by multiple attributes and create dictionary

Tags:

c#

format

key

linq

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.

like image 555
AwesomeGuy Avatar asked Jan 28 '26 15:01

AwesomeGuy


1 Answers

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

like image 185
DiplomacyNotWar Avatar answered Jan 30 '26 04:01

DiplomacyNotWar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!