在Linq中查找正则表达式匹配项的索引

3
我有一个定义为Dictionary<int,Regex>的字典。其中有许多已编译的Regex对象。这是使用C# .NET 4完成的。
我正在尝试使用Linq语句解析字典,并返回一个包含所有字典键以及每个正则表达式在指定文本中找到位置的对象。
ID成功返回,但我不确定如何获得发现文本的位置。有人能帮我吗?
var results = MyDictionary
    .Where(x => x.Value.IsMatch(text))
    .Select(y => new MyReturnObject()
        {
            ID = y.Key,
            Index = ???
        });

这个问题基本上与LINQ或字典无关,可以简化。 - usr
Dictionary<T,T2>没有索引。 - Daniel A. White
2个回答

2
请使用Match类的Index属性,而不是简单地使用IsMatch方法。

示例:

void Main()
{
    var MyDictionary = new Dictionary<int, Regex>() 
    {
        {1, new Regex("Bar")},
        {2, new Regex("nothing")},
        {3, new Regex("r")}
    };
    var text = "FooBar";

    var results = from kvp in MyDictionary
                  let match = kvp.Value.Match(text)
                  where match.Success
                  select new 
                  {
                        ID = kvp.Key,
                        Index = match.Index
                  };

    results.Dump(); 
}

结果

在此输入图片描述


这个截图功能是VS2012的默认功能吗? - Caster Troy
2
@Alex 不是的。在我的代码中看到的网格和Dump()方法都是LINQPad的一部分。 - sloth

0
你可以尝试使用基于List<T>.IndexOf方法的代码。
.Select(y => new MyReturnObject()
        {
            ID = y.Key,
            Index = YourDictionary.Keys.IndexOf(y.Key)
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接