我正在构建一个解析纯文本数据库文件并创建关联的程序,以便我可以从系统中导出附件。
Dictionary<string, string> AttachementsDictionary = new Dictionary<string, string>();
Dictionary<string, string> BacklogLookupDictionary = new Dictionary<string, string>();
Dictionary<string, BacklogItem> BacklogItemDictionary = new Dictionary<string, BacklogItem>();
BacklogItem CurrentBacklogItem = new BacklogItem();
Dictionary<string, Product> ProductDictionary = new Dictionary<string, Product>();
Product CurrentProduct = new Product();
string StoryScrumId = "";
Console.WriteLine("Loading Data From ScrumWorks Database");
//You need access to this server to run this locally.
string[] lines = System.IO.File.ReadAllLines(@"\\dxScrum01v\ScrumWorksPro\scrumworks\data\hypersonic\scrumworks.script");
Console.WriteLine("Creating Object Dictionaries");
foreach (string line in lines)
{
if (line.Contains("INSERT INTO ATTACHMENT"))
{
AttachementsDictionary.Add(line.Split('(', ',')[1], line.Split('\'', '\'')[1]);
}
if (line.Contains("INSERT INTO BACKLOGITEM_ATTACHMENT"))
{
if (!BacklogLookupDictionary.ContainsKey(line.Split('(', ',')[1]))
{
BacklogLookupDictionary.Add(line.Split(',', ')')[1], line.Split('(', ',')[1]);
}
}
if (line.Contains("INSERT INTO BACKLOGITEMEJB VALUES"))//-324048562862518297
{
CurrentBacklogItem.ProductScrumId = Regex.Split(line, ",(?=(?:[^']*'[^']*')*[^']*$)")[7];
CurrentBacklogItem.StoryTitle = Regex.Split(line, ",(?=(?:[^']*'[^']*')*[^']*$)")[12];
string test = line.Split('(', ',')[1];
BacklogItemDictionary.Add(line.Split('(', ',')[1], CurrentBacklogItem);
}
if (line.Contains("INSERT INTO PRODUCTEJB VALUES"))
{
CurrentProduct.ProductName = line.Split('\'', '\'')[1].Replace(@"'", string.Empty);
CurrentProduct.StoryPrefix = Regex.Split(line, ",(?=(?:[^']*'[^']*')*[^']*$)")[4].Replace(@"'", string.Empty);
ProductDictionary.Add(line.Split('(', ',')[1], CurrentProduct);
}
}
上面是创建字典的代码,我用它来处理SQL数据库中的关联关系。
当它运行时,它显示为BacklogItemDictionary正确填充:
添加到字典中的每个待办事项都是唯一的:
然而,一旦foreach循环结束,每个值都会变为相同的错误值:
每个键的每个BacklogItem对象与上面相同。我怎么做才能让dictonary这样做?我该如何解决?
答案 0 :(得分:9)
您可以在循环中创建BacklogItem
,而不是在循环之前创建BacklogItem
的一个实例,然后再重复使用。否则,您只是在每次迭代时更改单个实例的属性,实际上最后一行获胜。
所以而不是:
BacklogItem CurrentBacklogItem = new BacklogItem();
foreach (string line in lines)
{
.... (changes properties everytime and adds the same instance to the dictionary)
}
此...
foreach (string line in lines)
{
BacklogItem CurrentBacklogItem = new BacklogItem();
.... (initializes this object and adds it to the dictionary)
}