问题描述
我有这个对象:
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<>:
I have an IList<> of this object :
IList<MyObject> MyListObject = new List<MyObject>();
我在上面执行Linq查询:
I do a Linq query on it :
var result = (from p in MyListObject where p.FieldC == "Test" select p.FieldA);
在这种情况下,我返回"p.FieldA",但有时我需要返回"p.FieldB".我想将字段名称(FieldA或FieldB)放在这样的变量中
In this case, I return "p.FieldA" but sometimes I need to return "p.FieldB". I'd like put the name of the field (FieldA or FieldB) in a variable like this
var myvar = "FieldB"
var result = (from p in MyListObject where p.FieldC == "Test" select p.????);
如何在Linq查询中使用myvar内容(FieldB)作为字段名称?
How use myvar content (FieldB) as field name in the Linq query ?
谢谢
推荐答案
如果您的方法本身知道必须在FieldA和FieldB之间进行选择,则可以使用:
If your method itself knows it has to choose between FieldA and FieldB you can use:
var whatField = "FieldA";
var result = (from p in MyListObject
where p.FieldA == "Test"
select (whatField == FieldA ? p.FieldA : p.FieldB));
如果您有2个以上的选项,我会选择传递lambda;
If you have more as 2 options, I would choose to pass a lambda;
Func<MyObject, object> fieldGetter;
// Option A, switch
switch (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 like
var result = (from p in MyListObject
where p.FieldA == "Test"
select fieldGetter(p));
使用lambda的优点是,您可以拆分逻辑,什么字段以及如何查询.您甚至可以使其适用于不同类型:
The advantage of using the lambda is, you can split your logic, what field and how to query. And you can even make it work for different types:
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);
这篇关于使用LINQ将变量值用作字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!