LINQ: Convert Anonymous Type

I wanted to use an anonymous type with a report viewer control in ASP.NET... of course that doesn't work unless you have a strongly typed object. And here's how I did it:
/// <summary>
/// The class of object I want to return
/// </summary>
public class MyClass
{
public int id { get; set; }
public string text { get; set; }
}

/// <summary>
/// The class used as the data source
/// </summary>
public class SourceClass
{
public int source_id { get; set; }
public string source_text { get; set; }
public string source_unused { get; set; }
}

/// <summary>
/// The method that queries the data source
/// </summary>
/// <returns></returns>
public IEnumerable<MyClass> Get()
{
// strongly typed datasource
var list = new List<SourceClass>();
list.Add(new SourceClass { source_id = 1, source_text = "test 1", source_unused = "" });
list.Add(new SourceClass { source_id = 2, source_text = "test 2", source_unused = "" });
list.Add(new SourceClass { source_id = 3, source_text = "test 3", source_unused = "" });
list.Add(new SourceClass { source_id = 4, source_text = "test 4", source_unused = "" });

// query the list, map fields as new anonymous type
var results = from x in list
select new { id = x.source_id, text = x.source_text };

// pass into the method as array of objects (can't cast an anonymous type to anything else)
return ConvertAnonymousType<MyClass>(results.ToArray());
}

/// <summary>
/// Converts a list of objects into a list of strongly typed objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="anonymouslyTypedList"></param>
/// <returns></returns>
public static IEnumerable<T> ConvertAnonymousType<T>(IEnumerable<object> list)
{
var stronglyTypedList = (List<T>) Activator.CreateInstance(typeof(List<T>), null);

foreach (var item in list)
{
var obj = (T) Activator.CreateInstance(typeof(T), null);
foreach (System.Reflection.PropertyInfo pi in typeof(T).GetProperties())
{
var value = typeof(T).GetProperty(pi.Name).GetValue(item, null);
typeof(T).GetProperty(pi.Name).SetValue(obj, value, null);
}
stronglyTypedList.Add(obj);
}

return stronglyTypedList;
}

1 comment:

Debasish Das said...

May be you did some mistake its giving Error Object does not match target type.