I want to convert from
public class Party
{
public string Type { get; set; }
public string Name { get; set; }
public string Status { get; set;}
}
and convert to
public class Contact
{
public string Type { get; set; }
public string Name { get; set; }
public string Status { get; set;}
public string Company {get;set;}
public string Source {get;set;}
}
I tried using this extension method
public static class EnumerableExtensions
{
public static IEnumerable<TTo> ConvertTo<TTo, TFrom>(this IEnumerable<TFrom> fromList)
{
return ConvertTo<TTo, TFrom>(fromList, TypeDescriptor.GetConverter(typeof(TFrom)));
}
public static IEnumerable<TTo> ConvertTo<TTo, TFrom>(this IEnumerable<TFrom> fromList, TypeConverter converter)
{
return fromList.Select(t => (TTo)converter.ConvertTo(t, typeof(TTo)));
}
}
I get this error TypeConverter is unable to convert ‘Party’ to ‘Contact’
var parties = new List<Party>();
parties.Add(new Party { Name = "name 1", Status = "status 1" });
parties.Add(new Party { Name = "name 2", Status = "status 2" });
var results = parties.ConvertTo<Contact, Party>().ToList();
What am I missing here?
There is no direct conversion between the type Party and the Type contact (polymorphic or inheritance based).
You need to implement a TypeConverter for your types so that .NET knows how to convert between those two types:
MSDN – TypeConverter Class
MSDN – How to Implement a TypeConverter
Once you create your TypeConverters, you have to decorate your two classes with the TypeConverterAttribute so that the Framework can get an instance of your TypeConverter at Runtime:
You could also attempt to mimic the (what I’m guessing) is the desired behavior using LINQ (even though you’ll lose the generic abilities):