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

Map a list to single object

I receive a list of objects (these objects have to fields: type and value).
Ideally I’d like to filter some of these objects and return one object containing these fields.

At the moment i have this working solution to the problem:

List<PersonDataEntries> personDataEntriesList = PersonData.ToList();

return new Person(
    FirstName: personDataEntriesList.Where(x => x.Type.Equals("firstname")).Single().Value,
    LastName: personDataEntriesList.Where(x => x.Type.Equals("lastname")).Single().Value,
    BirthDay: DateTime.Parse(personDataEntriesList.Where(x => x.Type.Equals("birthday")).Single().Value),

Is there a more elegant solution to this? it just feels very clumsy…

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

>Solution :

You should turn your original list into a Dictionary, and then use that

var personDataEntriesDict = PersonData.ToDictionary(k => k.Type, v => v.Value);

return new Person(
    FirstName: personDataEntriesDict["firstname"],
    LastName: personDataEntriesDict["lastname"],
    BirthDay: DateTime.Parse(personDataEntriesDict["birthday"]))
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