开发者

How to get dynamic field in LINQ

Here's my LINQ query:

    var settingViewModels = from l in settingsByEnvironment["Localhost"]
                                join d in settingsByEnvironment["Dev"] on l.Key equals d.Key
                                join p in settingsByEnvironment["Prod"] on d.Key equals p.Key
                                select new MyKeyValue
                                {
                                    Key = p.Key,
                                    LocalhostValue = l.Value,
                                    DevValue = d.Value,
                                    ProdValue = p.Value
                                };

As you see, I've hard coded the three environment Localhost, Dev, and Prod in two parts of my code.

What if tomorrow, I have a new environment? My code is not dynamic.

I tried to use ExpandoObject, but still I cannot have a full dynamic query. Here's the equivalent of my previous LINQ code using ExpandoObject;

// listSettingsEnvLocalhost is of type Tuple<string (environmentName), List<SettingViewModels>>


    public void GetSettingsValueForEachEnvironment()
    {

       var foo = f开发者_如何学Crom p in listSettingsEnvLocalhost.Item2
           join a in listSettingsEnvDev.Item2 on p.Key equals a.Key
           let environmentLocalhost = listSettingsEnvLocalhost.Item1
           let environmentDev = listSettingsEnvDev.Item1
           select ToExpando(p, a, environmentLocalhost, environmentDev);
    }

    private dynamic ToExpando(SettingViewModel first, SettingViewModel second, string environmentLocalhost, string environmentDev)
    {
        dynamic o = new ExpandoObject();
        ((IDictionary<string, object>)o).Add("Key", first.Key);
        ((IDictionary<string, object>)o).Add(environmentLocalhost, first.Value);
        ((IDictionary<string, object>)o).Add(environmentDev, second.Value);
        return o;
    }

Is an expression tree a solution?


If you want create a dynamic query, you can use dynamic LINQ operators that are available at this link: http://msdn.microsoft.com/en-us/bb330936.aspx (download the C# example and get the code in the \LinqSamples\DynamicQuery directory)

There is also a dynamic Join operator defined by Royd Brayshay. See Stack Overflow question How to create a dynamic LINQ join extension method.


I would store your setting variables in a dictionary instead. Then it would be more dynamic. The dictionary should look like Dictionary<string, Dictionary<string, string>.

The first key is environment and the key in the inner dictionary is the settings key. Then you would be all set, and it would be dynamic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜