I have a function that filters objects of a specific class by a chosen field. The way I currently do this is that I pass a string naming the field as an argument to the function. Ideally I would want to be able to use this string to select the field in the object, similar to a dictionary (this functionality exists in javascript for example).
So I have the function (cut down to the relevant bits) here:
private List<HangingArtBundle> ConstrainBundlesBy(List<HangingArtBundle> bundles, string valueString, string constraint)
{
List<HangingArtBundle> retBundles = new List<HangingArtBundle>();
List<string> values = new List<string>(valueString.Split(new char[] { '|' }));
foreach (HangingArtBundle bundle in bundles)
{
if (values.Contains(ConstrainedField(constraint, bundle)))
{
retBundles.Add(bundle);
}
}
return retBundles;
}
I would like to be able to replace the ConstrainedField(constraint, bundle) part with something like bundle[constraint], where constraint is the name of a field of the class HangingArtBundle. Instead, I have to use this function below, which requires me to manually add field names as needed:
private string ConstrainedField(string field, HangingArtBundle bundle)
{
if (field.Equals("Category"))
{
return bundle.Category;
}
else if (field.Equals("AUToolTab"))
{
return bundle.AUToolTab;
}
else
{
return "";
}
}
If it helps at all, here is the class (essentially just a struct):
public class HangingArtBundle
{
public string CP { get; set; }
public string Title { get; set; }
public string Category { get; set; }
public string AUToolTab { get; set; }
public List<HangingArtEntry> Art { get; set; }
}
Is this possible to do in an elegant way in C#?
You can use
System.Reflectionfor thisOr perhaps an Extension method to make life a bit easier:
Usage: