Nerd in Training
Nerd in Training

Reputation: 2220

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 variable that tells me which Column they want the distinct values from???

Upvotes: 0

Views: 844

Answers (3)

Tigran
Tigran

Reputation: 62256

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.

Upvotes: 0

Kugel
Kugel

Reputation: 19824

I would use if. Why complicate this?

Upvotes: 0

Yahia
Yahia

Reputation: 70369

Try

List<object> test = (from x in BusinessObjectCollection select x.GetType().GetProperty ("thePropertyName").GetGetMethod().Invoke(x,null)).Distinct().ToList();

Upvotes: 2

Related Questions