C#Linq .ToDictionary()键已存在 [英] C# Linq .ToDictionary() Key Already Exists
问题描述
最终编辑:我能够在ini文件中找到重复的字段。感谢您的帮助每个人!
我正在使用正则表达式来解析ini文件和LINQ来将其存储在词典中:
I'm using a regular expression to parse an ini file and LINQ to store it in a Dictionary:
样本数据:
[WindowSettings]
窗口X Pos =' 0'
窗口Y Pos ='0'
窗口最大化='false'
窗口名称='Jabberwocky'
< br>
[日志]
目录='C:\Rosetta Stone\Logs'
Sample Data:
[WindowSettings]
Window X Pos='0'
Window Y Pos='0'
Window Maximized='false'
Window Name='Jabberwocky'
[Logging]
Directory='C:\Rosetta Stone\Logs'
编辑:这是导致问题的文件: http://pastebin.com/mQSrkrcP
EDIT2:我缩小了文件的最后一部分:[list_first_nonprintable]
由于某种原因,我正在解析的文件之一是抛出以下异常:
For some reason one of the files that I'm parsing with this is throwing this exception:
System.ArgumentException:具有相同键的项目已经存在en添加。
System.ArgumentException: An item with the same key has already been added.
有没有办法找出导致问题的哪个键(所以我可以修复文件) ,或者只是跳过导致此问题并继续解析的密钥?
Is there any way for me to either find out which key is causing the problem (so I can fix the file), or to just skip the key that's causing this and continue parsing?
这是代码:
try
{
// Read content of ini file.
string data = System.IO.File.ReadAllText(project);
// Create regular expression to parse ini file.
string pattern = @"^((?:\[)(?<Section>[^\]]*)(?:\])(?:[\r\n]{0,}|\Z))((?!\[)(?<Key>[^=]*?)(?:=)(?<Value>[^\r\n]*)(?:[\r\n]{0,4}))*";
//pattern = @"
//^ # Beginning of the line
//((?:\[) # Section Start
// (?<Section>[^\]]*) # Actual Section text into Section Group
// (?:\]) # Section End then EOL/EOB
// (?:[\r\n]{0,}|\Z)) # Match but don't capture the CRLF or EOB
// ( # Begin capture groups (Key Value Pairs)
// (?!\[) # Stop capture groups if a [ is found; new section
// (?<Key>[^=]*?) # Any text before the =, matched few as possible
// (?:=) # Get the = now
// (?<Value>[^\r\n]*) # Get everything that is not an Line Changes
// (?:[\r\n]{0,4}) # MBDC \r\n
// )* # End Capture groups";
// Parse each file into a Dictionary.
Dictionary<string, Dictionary<string, string>> iniFile
= (from Match m in Regex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
select new
{
Section = m.Groups["Section"].Value,
kvps = (from cpKey in m.Groups["Key"].Captures.Cast<Capture>().Select((a, i) => new { a.Value, i })
join cpValue in m.Groups["Value"].Captures.Cast<Capture>().Select((b, i) => new { b.Value, i }) on cpKey.i equals cpValue.i
select new KeyValuePair<string, string>(cpKey.Value, cpValue.Value)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
}).ToDictionary(itm => itm.Section, itm => itm.kvps);
return iniFile;
}
catch (ArgumentException ex)
{
System.Diagnostics.Debug.Write(ex.ToString());
return new Dictionary<string, Dictionary<string, string>>();
}
提前感谢
推荐答案
这只是意味着当您转换为词典 -
This just means that when you convert to a Dictionary --
.ToDictionary(itm => itm.Section, itm => itm.kvps);
- 有多个键(itm.Section)。您可以使用 ToLookup ,这是实物像一个字典,但允许多个键。
-- there are multiple keys (itm.Section). You can use ToLookup instead, which is kind of like a dictionary but allows multiple keys.
修改
几种方法来调用 ToLookup 。最简单的是指定键选择器:
There are a couple of ways to call ToLookup. The simplest is to specify the key selector:
var lookup =
// ...
.ToLookup(itm => itm.Section);
这应该提供一个关键字类型为组的查找。获取查询值应该返回一个IEnumerable,其中T是匿名类型:
This should provide a lookup where the key is of type Group. Getting a lookup value should then return an IEnumerable, where T is the anonymous type:
Group g = null;
// TODO get group
var lookupvalues = lookup[g];
如果.NET编译器不喜欢这个(有时似乎有麻烦弄清楚什么各种类型应该是),你也可以指定元素选择器,例如:
If the .NET compiler doesn't like this (sometimes it seems to have trouble figuring out what the various types should be), you can also specify an element selector, for example:
ILookup<string, KeyValuePair<string,string>> lookup =
// ...
.ToLookup(
itm => itm.Section.Value, // key selector
itm => itm.kvps // element selector
);
这篇关于C#Linq .ToDictionary()键已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!