Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LINQ GroupBy and select a list of other property values

I have pairs as such

public class AnalyteUnitPair
    {
        public string Analyte { get; set; }
        public string Unit { get; set; }
    }

and I need to turn the list of these into a reshuffled grouped by as such:

what I have

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Analyte ="Ce", Unit="g"
Analyte ="Ce", Unit="%"
Analyte ="Ce", Unit="ppm"
Analyte ="Dy", Unit="kg"
Analyte ="Dy", Unit="%"
Analyte ="Dy", Unit="ppm"

what I need is to convert the list above into the list of objects

public class AnalyteUnits
    {
        public string Analyte { get; set; }
        public string Units { get; set; }

    }

that would look like this

Analyte="Ce", Units="g:g,%:%,ppm:ppm";
Analyte="Dy", Units="kg:kg,%:%,ppm:ppm";

Please do not suggest Dictionary, I don’t want to deal with them on the JS side.

Thank you

>Solution :

First group by the Analyte, then you can select all the Units for each group.

var condensed = originalList
    .GroupBy(item => item.Analyte)
    .Select(group => new AnalyteUnitPair()
    {
        Analyte = group.Key,
        Unit = string.Join(",", group.Select(item => $"{item.Unit}:{item.Unit}"))
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading