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 = ???
        });
4

2 回答 2

2

使用类的Index属性Match而不是简单的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(); 
}

结果

在此处输入图像描述

于 2012-09-05T14:00:00.837 回答
0

您可以根据List<T>.IndexOf方法尝试使用此代码。

.Select(y => new MyReturnObject()
        {
            ID = y.Key,
            Index = YourDictionary.Keys.IndexOf(y.Key)
        });
于 2012-09-05T14:04:51.110 回答