2012-09-05 68 views
3

我有一个字典,定义为Dictionary<int, Regex>。这里有很多编译好的Regex对象。这是使用C#.NET 4完成的。在Linq查找正则表达式匹配的索引

我试图使用Linq语句来解析字典并返回一个包含所有字典的对象Keys和每个Regex在指定文本中找到的位置的索引。

身份证返回正常,但我不确定如何获取文本的位置。有人可以帮我吗?

var results = MyDictionary 
    .Where(x => x.Value.IsMatch(text)) 
    .Select(y => new MyReturnObject() 
     { 
      ID = y.Key, 
      Index = ??? 
     }); 
+0

这个问题基本上与LINQ或词典无关。它可以被简化。 – usr

+0

'词典'没有索引。 –

回答

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(); 
} 

结果

enter image description here

+0

这工作出色。谢谢! – Rethic

+0

截图:VS2012的默认功能是? –

+2

@Alex号您在我的代码中看到的网格和'Dump()'方法是[LINQPad](http://www.linqpad.net/)的一部分。 – sloth

0

您可以使用此代码尝试基于List<T>.IndexOf我的ThOD。

.Select(y => new MyReturnObject() 
     { 
      ID = y.Key, 
      Index = YourDictionary.Keys.IndexOf(y.Key) 
     });