我正嘗試做這樣的事情:的LINQ在以利用可變首
public class Person{string name;string surname;}
//...
List<Person> listExample;
//We add Person object in listExample
string variable="name";
listexample.Where(x=>x.(variable)=="John");
它是更多鈔票做同樣的事情?如果您需要訪問的屬性,那麼你可以使用GetProperties(BindingFlags bindingAttr)
方法而不是GetFields(...)
方法
class Person
{
public Person(string name)
{
this.name = name;
}
string name;
}
List<Person> people = new List<Person>()
{
new Person("Jane"),
new Person("John")
};
string variableName = "name";
string criteria = "John";
var selectedPeople =
people
.Where(person =>
typeof(Person)
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(fieldInfo => String.Equals(fieldInfo.Name, variableName))
.Select(fieldInfo => fieldInfo.GetValue(person) as string)
.SingleOrDefault() == criteria
)
.ToList();
// At this point 'selectedPeople' will contain one 'Person' named "John"
:
的可能的複製[如何創建謂詞動態](http://stackoverflow.com/questions/6383825/how-to-create-predicate-dynamically);也[動態創建一個表達式](http://stackoverflow.com/questions/5094489/how-do-i-dynamically-create-an-expressionfuncmyclass-bool-predicate-from-ex);也[動態創建謂語]](http://stackoverflow.com/questions/845059/how-do-i-dynamically-create-an-expressionfuncmyclass-bool-predicate) – ASh