Return distinct values dynamically
I have a class with this structure:
public class BusinessObject
{
public int Column5 { get; set; }
public int Column6 { get; set; }
public string Column7 { get; set; }
public int Column8 { get; set; }
}
and I have this line using LINQ:
List<int> test = (from x in BusinessObjectCollection select x.Column5).Distinct().ToList();
now this works nice.. but what if I don't know the property that the user wants the distinct values? What if all I have is a string var开发者_运维知识库iable that tells me which Column they want the distinct values from???
Try
List<object> test = (from x in BusinessObjectCollection select x.GetType().GetProperty ("thePropertyName").GetGetMethod().Invoke(x,null)).Distinct().ToList();
I would use if
. Why complicate this?
Try somethign like this pseudeocode! :
IQueryable<BusinessObject> filteredBoList = boList.AsQueryable();
Type boType= typeof(BusinessObject);
foreach(string filter in filterColumnNames) {
var found = filteredBoList.Where(p => (string)boType.InvokeMember(filter.FieldName,BindingFlags.GetProperty, null, p, null) == filter ).Distinct();
}
Should work.
Regards.
精彩评论