kosnkov
kosnkov

Reputation: 5911

Dynamic query with Linq

Is this possible to do sth as following:

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

and then

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

and is it possbile something like this?

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

Upvotes: 0

Views: 139

Answers (3)

Alexander Balte
Alexander Balte

Reputation: 900

Your sample looks strange. Each Month class has Jan property.

Update:

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;
    }
}

usage:

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

Upvotes: 2

Adam Bilinski
Adam Bilinski

Reputation: 1198

Note sure what is en expected value, but this would give you the value of the matching property.

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));

Upvotes: 3

Mahdi Tahsildari
Mahdi Tahsildari

Reputation: 13582

I suggest using enum for such cases, and there are lots of things you can do with enums, I bring an example :

Enum definition:

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

in button click :

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.
}

You can intanciate, you can compare, you can cast.
So why not use enums? When you have a car you needn't run.

Upvotes: 1

Related Questions