First and foremost this is really a bizarre thing to do. You should think of an alternate design first. There are a couple coming to me now.
Anyway you could use reflection to achieve what you are trying to achieve., well almost..
foreach (Dimension dimension in Enum.GetValues(typeof(Dimension)))
{
var r = new ReferenceTable(dimension).referenceItems;
var qry = TVRawDataList.Where(p => !r.Any(d => IsAMatch(p, dimension, d.Value)))
.ToList();
DimensionItem di = new DimensionItem(qry, dimension);
newDimensions.Add(di);
}
bool IsAMatch<T>(TVRawDataRecord obj, Dimension dimension, T valueToMatch)
{
return valueToMatch == dimension.MapToTvRecordProperty<T>(obj);
}
T MapToTvRecordProperty<T>(this Dimension dimension, TVRawDataRecord obj)
{
return obj.GetPropertyValue<T>(dimension.ToString());
}
T GetPropertyValue<T>(this TVRawDataRecord obj, string propertyName)
{
var property = typeof(TVRawDataRecord).GetProperty(propertyName);
if (property == null)
return null; //or throw whatever
return (T)property.GetValue(obj, null);
}
Strictly untested, uncompiled. But this should give an idea how it is done. You can make the GetPropertyValue
function more generic, but that's a different thing. The T
type argument in Map
function (that maps a dimension enum to property of TVRawDataRecord
class) is passed since you need to know the return type of the property.
I would say a better alternate design is just to make a simple function that uses if else logic to return the right type. So change Map
function to this:
T MapToTvRecordProperty<T>(this Dimension dimension, TVRawDataRecord obj)
{
switch (dimension)
{
case Dimension.BrandVariant:
return obj.BrandVariant;
case Dimension.Creative:
return obj.Creative;
.....
default:
throw;
}
}
The advantage is that even if in future you change the name of any of the variables, your code wouldn't break (unlike the reflection approach). But the catch here is to choose the return type T
. The second example wouldnt compile since return type doesnt match what is being returned. If all the properties are of the same type, then you can choose that type. If it's so really variable, then you will have to cast your property first to object and then to T
, but still better than reflection!!
An even better approach would be to specify attributes either to property or to enum.
And best of all if BrandVariant
and Creative
etc are classes of their own, you can make them all implement an interface which will have a property readonly Dimension
on them and you can access that property of your tv record properties to get the right dimension value!