这个伪代码的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 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
复制相似问题