CSharp · Console
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var myDatabase = new
{
Persons = new DbPerson[]
{
new DbPerson { GivenName = "Alice", FamilyName = "Smith", AltGivenName = "AFoo" },
new DbPerson { GivenName = "Bob", FamilyName = "Hancock", AltGivenName = "BBar" }
}
};
var persons = myDatabase.Persons.Select(MappingHelper.ToPerson);
var anonPersons = myDatabase.Persons.Select(MappingHelper.ToAnonymousPerson);
Console.WriteLine(string.Join(", ", persons));
Console.WriteLine(string.Join(", ", anonPersons));
}
}
public static class MappingHelper
{
public static Person ToPerson(this DbPerson dbPerson)
{
return new Person
{
GivenName = dbPerson.GivenName,
FamilyName = dbPerson.FamilyName
};
}
public static AnonymousPerson ToAnonymousPerson(this DbPerson dbPerson)
{
return new AnonymousPerson
{
Nickname = dbPerson.AltGivenName
};
}
}
public class DbPerson
{
public string GivenName { get; set; }
public string FamilyName { get; set; }
public string AltGivenName { get; set; }
}
public class Person
{
public string GivenName { get; set; }
public string FamilyName { get; set; }
public override string ToString() => $"{GivenName} {FamilyName}";
}
public class AnonymousPerson
{
public string Nickname { get; set; }
public override string ToString() => Nickname;
}