I'm trying to create a generic function within my application, and the one thing holding me up is a lambda expression that relies on knowing the object primary key.
eg. I'm extracing a list of PrimaryKey values from a list of records. This list of records could be a variety of different types, hence the name of the Primary Key field can be different. At present, I'm using the following code where (in this case), the list of items is of type ReportCategoryEntity, however this list could be one of many different class types.
string primaryKeyName = "ReportCategoryID";
List<long> ids = items.Select(c => c.ReportCategoryID).ToList();
However, I would like to have something like:
string primaryKeyName = "ReportCategoryID";
List<long> ids = items.Select(c => c.[primaryKeyName]).ToList();
I have reviewed some other questions that suggest using Dynamic Linq (LINQ : Dynamic select), however all examples return a list of the original class object (eg. List). I'm trying to return a simple list of type long of the Ids, without the other fields of the data object.
UPDATE: I'm currently using a work-around. Not hugely elegant, but it works.
I've now got a static function that will find the value of an object's property:
public static T GetPropertyValue<T>(object obj, string propName)
{
return (T)obj.GetType().GetProperty(propName).GetValue(obj, null);
}
I can use this within my generic table processing function to find the value where = ReportCategoryEntity
string sql = "Select * From ReportCategories Where ReportID = 1;";
string primaryKeyName = "ReportCategoryID";
var primaryIds = new List<long>();
var items = await _dbCloud.QueryAsync<T>(sql);
foreach (var i in items)
{
var v = Helpers.GetPropValue(i, primaryKeyName);
primaryIds.Add(long.Parse(v.ToString()));
}