【发布时间】:2016-02-11 01:42:11
【问题描述】:
我正在尝试将数据存储在带有键的排序字典中,值是另一个字典。
我已经定义了一个类:
public class Search_Config_Out_List
{
public string _Env { get; set; }
public string _Interface { get; set; }
public string _System { get; set; }
public string _Timeframe { get; set; }
public string _Dir { get; set; }
public string _Filename { get; set; }
public string _LogDir { get; set; }
public string _LogFile { get; set; }
public Search_Config_Out_List(string Env, string Interface, string System, string Timeframe, string Dir, string Filename, string LogDir, string LogFile)
{
_Env = Env;
_System = System;
_Interface = Interface;
_Timeframe = Timeframe;
_Dir = Dir;
_Filename = Filename;
_LogDir = LogDir;
_LogFile = LogFile;
}
}
定义:
SortedDictionary<string, Dictionary<string, Search_Config_Out_List>> dA =
new SortedDictionary<string, Dictionary<string, Search_Config_Out_List>>();
List<Search_Config_Out_List> lsSearch_Config_Out_List = new List<Search_Config_Out_List>();
此时,我一直在循环通过一个 XML 文件检索数据。可以有 2 种类型:1 用于“Today”,1 用于“Older”,用于同一键。
lsSearch_Config_Out_List.Clear();
lsSearch_Config_Out_List.Add(
new Search_Config_Out_List(nodeALL.Attributes["Name"].Value.ToString(),
childENV.Attributes["Name"].Value.ToString(),
intALL.Attributes["Name"].Value.ToString(),
intDTL.Attributes["Name"].Value.ToString(),
sDir,
sFilename,
sLogDir,
sLogFile));
//sKey is the key for dA
string sKey = nodeALL.Attributes["Name"].Value.ToString()
+ "-" + childENV.Attributes["Name"].Value.ToString()
+ "-" + intALL.Attributes["Name"].Value.ToString();
//sKey2 is the key for the inside Dictionary (possible values are 'Today' and 'Older'
string sKey2 = intDTL.Attributes["Name"].Value.ToString();
dLine = new Dictionary<string, List<string>>();
if (!dLine.ContainsKey(sKey2))
dLine.Add(sKey2, new List<string>());
//Store in Dictionary
dLine[sKey2].Add(lsSearch_Config_Out_List); "****ERROR has invalid arguments
dA = new SortedDictionary<string, Dictionary<string, Search_Config_Out_List>>();
if (!dA.ContainsKey(sKey))
dA.Add(sKey, new Dictionary<string, Search_Config_Out_List>());
dA[sKey].Add(dLine); "**ERROR has invalid arguments
最后我希望字典存储这样的内容:
KEY="TEST-1"
VALUE[0] KEY="TODAY"
VALUE[0] Line1
VALUE[1] Line2
VALUE[2] Line3
VALUE[1] KEY="OLDER"
VALUE[0] Line1
VALUE[1] Line2
KEY="TEST-2"
VALUE[0] KEY="TODAY"
VALUE[0] Line1
VALUE[1] KEY="OLDER"
VALUE[0] Line1
我尝试了 Internet 上建议的几种不同方法,但要么出现错误,要么在添加“旧”键值时,它也覆盖了“今天”值。所以我已经为此苦苦挣扎了几天。
任何帮助将不胜感激。如果你能提供一个正确代码的例子,那将是有利的。
谢谢, 安德鲁
【问题讨论】:
-
你把它叫做
.Add([value])而不是.Add([key],[value]) -
Idk 如果只有我,但您的代码很难阅读 - 也许我只是累了。但是 Mathus 是正确的,你错过了你的
Key定义。我认为您的Dictionary声明也有问题,但重新阅读了几次,我知道发生了什么。 -
您使用的命名约定是一团糟。考虑遵循 C# 命名准则。
-
如果我将其更改为 dLine.Add(sKey2, lsSearch_Config_Out_List);我仍然收到错误 - 参数 2:无法从 'System.Collections.Generic.List
' 转换为 'System.Collections.Generic.List ' -
对不起命名约定,但我一直在复制/粘贴/复制/粘贴互联网上的建议,试图遵循其他人的做法
标签: c# list dictionary