Arun Rana
Arun Rana

Reputation: 8606

Dynamically select property in Linq query

I am facing one issue with linq query in c# , my linq query as per below

list = (from row in dt.AsEnumerable()
                            select new Perfmon
                            {
                                id = row.Field<long>("id"),
                                counter1 = row.Field<string>("counter"),

                            }).ToList();

I have one perfmon class and it contains properties like (id, counter1, counter2 ...) there are more then 20 counters now i have developed sql query to select id and counter based on passed countername in parameter e.g. if i have passed counter1 then it will select id , counter1 (renamed as counter) only

if i will use switch case here then it will have 20 witch case, can anyone please help me how can bind property dynamically in linq?

Thanks in advance.

Upvotes: 2

Views: 3105

Answers (3)

Tipx
Tipx

Reputation: 7505

I think you should look into the System.Reflection namespace. Sure, you want to use it within a linq query, but the thing you can't seem to do, for now, is to dynamically extract a field/property from a class.

Try to use it outside a linq query, and then you'll find a way to integrate it into your query.

Upvotes: 0

Anand
Anand

Reputation: 14915

You can also use Dynamic Linq. The essence is to parse your string and convert it in to expression trees. See here for more details

http://weblogs.asp.net/rajbk/archive/2007/09/18/dynamic-string-based-queries-in-linq.aspx

Upvotes: 0

Polity
Polity

Reputation: 15130

You can make your Perfmon class backed by a dictionary rather than fields per properties. like:

class Perfmon
{
    private readonly Dictionary<string, string> _counters = new Dictionary<string, string>();

    public Perfmon(params KeyValuePair<string, string>[] knownCounters)
    {
        foreach (var knownCounter in knownCounters)
        {
            SetCounter(knownCounter.Key, knownCounter.Value);
        }
    }   
    public void SetCounter(string name, string value)
    {
        _counters[name] = value;
    }

    protected string GetCounterValue(string name)
    {
        if (_counters.ContainsKey(name))
            return _counters[name];
        else
            return null;
    }

    public string Counter1 { get { return GetCounterValue("Counter1"); } }
    public string Counter2 { get { return GetCounterValue("Counter2"); } }
    public string Counter3 { get { return GetCounterValue("Counter3"); } }
}

The constructor is there so you can easily use it in your query like:

var counterName = "Counter2";
list = (from row in dt.AsEnumerable() 
                            select new Perfmon(new KeyValuePair<string, string>(counterName, row.Field<string>("counter")))
                            { 
                                id = row.Field<long>("id")
                            }).ToList();

Upvotes: 2

Related Questions