Dynamically select property in Linq query

前端 未结 3 1038
孤街浪徒
孤街浪徒 2021-01-21 19:15

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
            


        
相关标签:
3条回答
  • 2021-01-21 19:53

    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.

    0 讨论(0)
  • 2021-01-21 19:57

    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();
    
    0 讨论(0)
  • 2021-01-21 19:57

    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

    0 讨论(0)
提交回复
热议问题