Home > Software engineering >  Map a list to single object
Map a list to single object

Time:09-12

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...

CodePudding user response:

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"]))

CodePudding user response:

what about writing a delagate:

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

Func<string,string> selector =(type) => personDataEntriesList.Where(x => x.Type.Equals(type)).Single().Value;

return new Person(
    FirstName: selector ("firstname"),
    LastName:selector ("lastname"),
    BirthDay: DateTime.Parse (selector ("birthday"))
  • Related