简体   繁体   中英

dynamic property name in linq

I'm trying to write a linq query that takes a dynamic property name. So for example, if the property name is 'test', a simple query would look like this:

var test = testList.Select(x => x.test).Distinct().ToList();

But I want to dynamically generate the property name, eg:

var propertyName = "test";

var test = testList.Select(x => x.propertyName).Distinct().ToList();

I get an error because 'propertyName' isn't an actual property.

What would be the best way to achieve this?

You'd have to use reflection to do what you're trying to do:

var test = testList
               .Select(x => x.GetType().GetProperty(propertyName).GetValue(x))
               .Distinct()
               .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM