Initialize Dictionary<t,t> &#34;on the fly&#34;

时间:2016-03-02 10:56:47

标签: c#

I have the following classes

public class PLCWrapper
{
    public int plc_id { get; set; }
    public List<SchakelingWrapper> schakelingWrapperList { get; set; }
    public Dictionary<string, string> globalVarDict { get; set; }
}

public class SchakelingWrapper
{
    public int schakeling_id { get; set; }
    public Dictionary<string, string> varDict { get; set; }
}

I wanna do something like below, but cann't get it fixed. Sure somebody knows how?

if (plcWrapper.schakelingWrapperList.Exists(item => item.schakeling_id == id)) {
    plcWrapper.schakelingWrapperList.Single(item => item.schakeling_id == id).varDict.Add(varName, varValue);
} else {
    plcWrapper.schakelingWrapperList.Add(new SchakelingWrapper()
    {
        schakeling_id = id,
        varDict = new Dictionary<string, string>(varName, varValue)//This does not work
    });
}

2 个答案:

答案 0 :(得分:2)

它需要像......

varDict = new Dictionary<string, string>()
{
    {varname, varvalue}
}

答案 1 :(得分:1)

更改此行
varDict = new Dictionary<string, string>(varName, varValue)//This does not work

varDict = new Dictionary<string, string>() {{varName, varValue}}