Dynamically select property in Linq query

前端 未结 3 1037
孤街浪徒
孤街浪徒 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:57

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

    class Perfmon
    {
        private readonly Dictionary _counters = new Dictionary();
    
        public Perfmon(params KeyValuePair[] 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(counterName, row.Field("counter")))
                                { 
                                    id = row.Field("id")
                                }).ToList();
    

提交回复
热议问题