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