Reputation: 3322
I have a generic method that takes a list of T as a parameter. I am trying to get certain data based on the type of interface and populate only those properties of each item in the list, that are defined in the interface.
So my base interface is:
public interface IStatusResult
{
int Status { get; set; }
string StatusName { get; set; }
}
I have a number of other interfaces that implement this interface, which i want to use to figure out what Status/Status Names key/value pairs to retrieve:
public interface IROQStatusResult: IStatusResult { }
public interface IOrderStatusResult: IStatusResult { }
public interface IActivityStatusResult: IStatusResult { }
Finally, i implement this interface in my search result class:
public class RecommendedOrderQuantitySearchResult:IROQStatusResult {
public int Id { get; set; }
public DateTime TargetDate { get; set; }
public int Status { get; set; }
public string StatusName { get; set; }
}
So once a get a List from the Db i want to set the status names in the Generic method:
public static List<T> PopulateStatusNames<T>(List<T> items) where T:class
{
Dictionary<int, string> statuses = new Dictionary<int, string>();
if (typeof(IROQStatusResult).IsAssignableFrom(typeof(T))) {
statuses = GlobalConstants.GetROQStatuses();
}
if (typeof(IOrderStatusResult).IsAssignableFrom(typeof(T))){
statuses = GlobalConstants.GetOrderStatuses();
}
foreach (var item in items)
{
item.StatusName = statuses[item.Status];
}
return items;
}
Currently, item.StatusName
is giving me an error: Item does not have property StatusName
How can i implement this?
Upvotes: 2
Views: 51
Reputation: 77294
Use OfType
, it will return only those that can be safely cast into the type:
foreach (var item in items.OfType<IStatusResult>())
{
item.StatusName = statuses[item.Status];
}
Upvotes: 5