这个伪代码的C#等价物是什么?
var pattern = ...;
var lookup = new Dictionary<string, string>();
foreach (var group in new Regex(pattern).Matches())
{
lookup[group.Name] = group.Value;
}我没有看到任何公开组名的与System.Text.RegularExpressions组相关的对象。
我遗漏了什么?
我实际上要做的是转换一个包含以下格式行的文件:
eventName|message|date到IEnumerable<EventLogLine>,其中EventLogLine为:
public struct EventLogLine
{
public string EventName { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
}并将这些行放入IDictionary<string /*EventName*/, IEnumerable<EventLogLine>>.中
发布于 2010-10-12 11:46:38
我只是在使用LINQ的时候把这个搞砸了。它依赖于用文件中的行填充的List<string>。
var lines = new List<string>();
var dict = lines.Select(l =>
{
var sp = l.Split('|');
return new EventLogLine { EventName = sp[0], Message = sp[1], Date = DateTime.Parse(sp[2]) };
})
.GroupBy(e => e.EventName)
.ToDictionary(grp => grp.Key, grp => grp.AsEnumerable());基本上,您使用Select()将每一行转换为EventLogLine,然后使用GroupBy()基于EventName创建分组,然后使用ToDictionary()运行查询并以所需格式创建字典!
发布于 2010-10-12 12:42:22
我认为你应该看看阿拉斯泰尔的答案,因为你的输入是如此简单,如果你只使用ReadLine和Match.Groups MSDN article.,以后阅读代码可能会更容易。
发布于 2010-10-12 22:39:22
考虑使用ToLookup而不是ToDictionary。通过不可变和公开一个非常简单的API,查找可以很自然地与linq和泛型代码一起工作。另外,我会将解析封装到EventLogLine结构中。
因此,代码将如下所示:
IEnumerable<string> lines;
ILookup<string, EventLogLine> lookup =
lines.Select(EventLogLine.Parse).ToLookup(evtLine => evtLine.EventName);一个示例消费者:
if(lookup["HorribleEvent"].Any())
Console.WriteLine("OMG, Horrible!");
foreach(var evt in lookup["FixableEvent"])
FixIt(evt);
var q = from evtName in relevantEventNames
from evt in lookup[evtName]
select MyProjection(evt);请注意,您不需要检查键是否存在,这与字典不同:
if(dictionary.ContainsKey("HorribleEvent")) //&& dictionary["HorribleEvent"].Any() sometimes needed
Console.WriteLine("OMG, Horrible!");
if(dictionary.ContainsKey("FixableEvent"))
foreach(var evt in lookup["FixableEvent"])
FixIt(evt);
var q = from evtName in relevantEventNames.Where(dictionary.ContainsKey)
from evt in dictionary[evtName]
select MyProjection(evt);正如您可能注意到的,使用包含IEnumerable值的字典引入了细微的摩擦-- ILookup正是您想要的!
最后,修改后的EventLogLine
public struct EventLogLine {
public string EventName { get; private set; }
public string Message { get; private set; }
public DateTime Date { get; private set; }
public static EventLogLine Parse(string line) {
var splitline = line.Split('|');
if(splitline.Length != 3) throw new ArgumentException("Invalid event log line");
return new EventLogLine {
EventName = splitline[0],
Message = splitline[1],
Date = DateTime.Parse(splitline[2]),
};
}
}https://stackoverflow.com/questions/3911443
复制相似问题