我有这个对象:public class MyObject{ public int Id { get; set; } public string FieldA { get; set; } public string FieldB { get; set; } public string FieldC { get; set; } public string FieldD { get; set; }}我有一个IList 这个对象:IList<MyObject> MyListObject = new List<MyObject>();我对此执行Linq查询:var result = (from p in MyListObject where p.FieldC == "Test" select p.FieldA);在这种情况下,我返回“ p.FieldA”,但有时我需要返回“ p.FieldB”。我想将字段名称(FieldA或FieldB)放在这样的变量中var myvar = "FieldB"var result = (from p in MyListObject where p.FieldC == "Test" select p.????);如何在Linq查询中使用myvar内容(FieldB)作为字段名称?谢谢, (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 如果您的方法本身知道必须在FieldA和FieldB之间进行选择,则可以使用:var whatField = "FieldA";var result = (from p in MyListObject where p.FieldA == "Test" select (whatField == FieldA ? p.FieldA : p.FieldB));如果您有2个以上的选项,我会选择传递一个lambda。Func<MyObject, object> fieldGetter;// Option A, switchswitch (whatField) { case "FieldA": fieldGetter = o => o.FieldA; break; case "FieldB": fieldGetter = o => o.FieldB; break; // More options}// Option B using reflection:var t = typeof(MyObject);var prop = t.GetProperty(whatField);fieldGetter = o => prop.GetValue(o, null);// Linq then looks likevar result = (from p in MyListObject where p.FieldA == "Test" select fieldGetter(p));使用lambda的优点是,您可以拆分逻辑,拆分哪个字段以及如何查询。您甚至可以使其适用于不同类型:IEnumerable<T> Query<T>(IQueryable<MyObject> MyListObject, Func<MyObject, T> fieldGetter) { return result = (from p in MyListObject where p.FieldA == "Test" select fieldGetter(p));}// call using:var result = Query(MyListObject, o => o.FieldA); (adsbygoogle = window.adsbygoogle || []).push({}); 10-08 19:00