使用Linq进行动态查询

时间:2013-01-14 09:27:12

标签: c# linq

这可能做得如下:

public class Months
{
    public double Jan {get;set;}
    public double Feb {get;set;}
    public double Mar {get;set;}
}

然后

List<Months> myList = new List<Months>();
string monthName = "Jan";

是否可能是这样的?

myList.where(x=>x.PropertyName.Equals(monthName))

3 个答案:

答案 0 :(得分:3)

请注意确定期望值是什么,但这会为您提供匹配属性的值。

List<Months> myList = new List<Months>();
myList.Add(new Months(){ Jan = 2.2});
string monthName = "Jan";
var result = myList.Select(x => x.GetType().GetProperty(monthName).GetValue(x, null));

答案 1 :(得分:2)

你的样本看起来很奇怪。每个Month类都有Jan属性。

<强>更新

public class Months
{
    private readonly IDictionary<string, double> _backfiends;

    public double Jan
    {
        get { return _backfiends["Jan"]; }
        set { _backfiends["Jan"] = value; }
    }

    public IDictionary<string, double> Backfields
    {
        get { return _backfiends; }   
    }

    public Months()
    {
        _backfiends = new Dictionary<string, double>();
        _backfiends["Jan"] = 0;
    }
}

用法:

var myList = new List<Months>();
myList.Add(new Months(){Jan = 123});
var withJan = myList.Select(x => x.Backfields["Jan"]);

答案 2 :(得分:1)

我建议在这种情况下使用枚举,你可以用枚举做很多事情,我举个例子:

枚举定义:

public enum Month 
{ Jan=1, Feb, Mar, Apr, may, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
点击按钮

Month current = Month.Jan; //staticly checking a month

if(current == Month.Jan)
    MessageBox.Show("It's Jan");
else
    MessageBox.Show("It's not Jan.");

List<Month> specialMonthes = new List<Month>();
specialMonthes.Add(Month.Oct);
specialMonthes.Add(Month.Apr);
specialMonthes.Add(Month.Jan);
//Search the list for the month we are in now
foreach (Month specialMonth in specialMonthes)
{
    if ((int)specialMonth == DateTime.Now.Month) //dynamically checking this month
        MessageBox.Show(string.Format("It's {0} now & {0} is a special month.",  
            specialMonth));
        //Output: It's Jan now and Jan is a special month.
}

你可以隐身,你可以比较,你可以施放。
那么为什么不使用枚举?当你有车时,你不需要跑。