- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
最终编辑:我能够在 ini 文件中找到重复的字段。感谢大家的帮助!
我正在使用正则表达式解析 ini 文件,并使用 LINQ 将其存储在字典中:
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]
出于某种原因,我正在解析的其中一个文件抛出了这个异常:
System.ArgumentException: An item with the same key has already been added.
有什么方法可以让我找出导致问题的键(这样我就可以修复文件),或者跳过导致这个问题的键并继续解析?
代码如下:
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>>();
}
提前致谢。
最佳答案
这只是意味着当您转换为字典时——
.ToDictionary(itm => itm.Section, itm => itm.kvps);
-- 有多个键(itm.Section)。您可以使用 ToLookup相反,它有点像字典,但允许多个键。
编辑
有几种方法可以调用 ToLookup。最简单的是指定键选择器:
var lookup =
// ...
.ToLookup(itm => itm.Section);
这应该提供一个查询,其中键是 Group 类型。获取查找值应该返回一个 IEnumerable,其中 T 是匿名类型:
Group g = null;
// TODO get group
var lookupvalues = lookup[g];
如果 .NET 编译器不喜欢这样(有时它似乎无法确定各种类型应该是什么),您还可以指定一个元素选择器,例如:
ILookup<string, KeyValuePair<string,string>> lookup =
// ...
.ToLookup(
itm => itm.Section.Value, // key selector
itm => itm.kvps // element selector
);
关于C# Linq .ToDictionary() 键已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625879/
我想调用一个返回匿名类型的方法。我需要知道这个匿名类型的类型是什么,因为我在一个方法中返回它。这叫“动态”吗?当我调试时,监 window 口显示类型是 <>f__AnonymousType0。 这是
关于 ToDictionary() 的 MSDN 文档并没有多说它实际上是如何工作的。我想知道它是创建字典及其元素的副本,还是只是重复使用相同的引用和枚举器。 例如,如果我有一个 Concurrent
给定以下代码,我无法返回字典。 [JsonProperty] public virtual IDictionary JsonProducts { get { retur
我有一个返回列表的方法,我们称它为GetSomeStrings() . 我在字符串类上有一个扩展方法,返回字符串中的字符数,例如。 myString.Number('A') . 我想在一行中获取字典。
我有一个简单的 LINQ 语句,它拆分一个字符串,然后将值扔到字典中。问题是字典很少已经具有相同值的现有键,因此抛出异常并且“dict”的值保持为空。 dict = lines.Select(l =>
我正在使用 Enumerable.ToDictionary 从 linq 调用中创建一个字典: return (from term in dataContext.Terms where
这个问题在这里已经有了答案: How do you get the duplicate key that ToDictionary() has failed on? (4 个答案) 关闭 7 年前。
我有如下两个模型: public class Complaint { [Key] public int COMP_ID { get; set; } public Nullabl
我不是 C# 和 LINQ 方面的专家。 我有一个Dictionary,我理解是一个哈希表,也就是key没有排序。 dataBase = new Dictionary() Record 是一个用户定义
我有一个像 string strn = "abcdefghjiklmnopqrstuvwxyz" 这样的字符串,并且想要一个像这样的字典: Dictionary(){ {'a',0},
我有一个简单的 Linq 查询: var dict = (from i in Customers select i).ToDictionary(i => i.Id1, i => i.Id2); 尽管查
我有一个字典,我想使用以下示例隐含的规则将其转换为另一个字典: 输入: Dictionary inputs = new Dictionary(3) { { "A", "First" },
最终编辑:我能够在 ini 文件中找到重复的字段。感谢大家的帮助! 我正在使用正则表达式解析 ini 文件,并使用 LINQ 将其存储在字典中: Sample Data: [WindowSetting
我有两个大小相同的字符串列表。我想创建一个字典,键来自listA,值来自listB。 什么是最快的方法? 我使用了代码: List ListA; List ListB;
我有一个要放入字典中的列表,为简单起见,插入的值将全部相同。 我可以使用 foreach 循环。 List list = new List(); list.Add("Earth");
我正在使用 IEnumerable 的 ToDictionary() 扩展方法创建一个 Dictionary 对象: var dictionary = new Dictionary (myCo
如何使用 Linq 将 SQL (2008) 中的两列正确转换为 Dictionary(用于缓存)? 我目前循环遍历 IQueryable b/c 我无法使 ToDictionary 方法工作。有任何
我正在寻找一种获取以下列表的方法: directory = [ { name: "Albert", age: 40, gender: "M"
ExSwift 有一个数组扩展: /** Converts the array to a dictionary with keys and values supplied via th
我有以下代码 public class TestAdaptor { private interface ITargetClass { Guid Id { get; }
我是一名优秀的程序员,十分优秀!