本文介绍了在Linq查询动态地选择属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在面临的LINQ查询一个问题在C#中,我的LINQ查询按以下

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



我有一个的perfmon 类,它包含像(ID,C1​​的特性,C2的...)
有更多然后20​​个柜现在我已经开发了SQL查询,根据参数传递如要countername选择ID和反如果我已经通过了C1的那么它将选择ID,C1​​的(更名为计数器)仅

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

如果我在这里用开关情况,那么就会有20个魔女的情况下,任何人都可以请帮助我如何可以动态地在LINQ绑定属性?

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?

在此先感谢。

推荐答案

您可以通过字典的支持,而不是每个属性的字段的性能监视器类。这样的:

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

这篇关于在Linq查询动态地选择属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 02:37