我正在使用c#中的linq查询遇到一个问题,我的linq查询如下
list = (from row in dt.AsEnumerable() select new Perfmon { id = row.Field<long>("id"), counter1 = row.Field<string>("counter"), }).ToList();
我有一个 perfmon 类,它包含诸如(id,counter1,counter2 …)之类的属性,现在有20多个计数器,我已经开发了sql查询以根据参数中传递的计数器名称选择id和计数器,例如,如果我已经传递了counter1,它将仅选择id,counter1(重命名为counter)
如果我将在这里使用开关盒,那么它将有20个女巫盒,有人可以帮我如何在linq中动态绑定属性吗?
提前致谢。
您可以使Perfmon类有字典支持,而不是由每个属性的字段支持。喜欢:
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"); } } }
构造函数在那里,因此您可以轻松地在查询中使用它,例如:
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();