I'm having a problem casting with C#
First, my auxiliary functions for better understanding
public static class Extensions {
public static IEnumerable<T> ToEnumerable<T>(this T value) {
yield return value;
}
public static dynamic ToDynamic(this object value) {
IDictionary<string, object> e = new ExpandoObject();
foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(value.GetType())) { e.Add(item.Name, item.GetValue(value));
return e;
}
public static IEnumerable<T> ToCast<T>(this IEnumerable<object> value, T sample) where T: class {
return null; /* HELP */
}
public static T ToCastFirstorDefault<T>(this object value, T sample) where T: class {
return value.ToEnumerable().ToCast(sample).Take(1).FirstOrDefault();
}
}
On the controller side there is an object data as seen in the example
object Model = new { take = 10, data = new object[] { new { tarih = DateTime.MaxValue, proje = "Lorem Ipsum", durum = true } } };
I can use it in .cshtml page side by using ToDynamic, ToEnumerable functions
var dy = Model.ToEnumerable().Select(x => x.ToDynamic()).Select(x => new
{
take = (int)x.take,
data = ((object[])x.data).Select(y => y.ToDynamic()).Select(y => new
{
tarih = (DateTime)y.tarih,
proje = (string)y.proje,
durum = (bool)y.durum
})
}).Take(1).FirstOrDefault();
Although this build works 100% correctly, not user-friendly at all when there are more properties
I want so that I can use the ToCast, ToCastFirstorDefault functions as I wrote in the example below. Is it possible?
var rslt = Model.ToCastFirstorDefault(new {
take = 0,
data = default(object[])
});
Or:
var rslt = Model.ToCastFirstorDefault(new {
take = 0,
data = default(object[])
}).ToEnumerable().Select(x=> new {
x.take,
data = x.data.ToCast(new { tarih = default(DateTime), proje = "", durum = false })
}).Take(1).FirstOrDefault();
I couldn't use Convert.ChangeType because of the anonymous type.