Tutaj przychodzi z pomocą magiczne narzędzie jakim jest refleksja!
Poniższy kod kopiuje wartości z obiektu źródłowego do docelowego pod warunkiem, że mają tą samą nazwę i są tego samego typu.
public static void CopyPropertiesTo<T, TU>(this T source, TU dest)
{
List<PropertyInfo> sourceProps = typeof(T).GetProperties().Where(x => x.CanRead).ToList();
List<PropertyInfo> destProps = typeof(TU).GetProperties().Where(x => x.CanWrite).ToList();
foreach (PropertyInfo sourceProp in sourceProps)
{
PropertyInfo p = destProps.FirstOrDefault(x => x.Name == sourceProp.Name);
if (p is null) continue;
if (p.CanWrite)
{
p.SetValue(dest, sourceProp.GetValue(source, null), null);
}
}
}
Zwróć uwagę, że jest to metoda typu rozszerzenie (extension), jak będziesz miał z nią problem, to usuń słówko this z pierwszej linijki.
P.S. Metodę tę znalazłem kiedyś gdzieś na StackOverflow.