【问题标题】:Linq search - Display small part of searched textLinq 搜索 - 显示搜索文本的一小部分
【发布时间】:2013-08-14 17:04:16
【问题描述】:

我正在尝试使用 linq 实现文本搜索。我有一个 Messages 表,其中填充了电子邮件数据。我希望能够在消息正文中进行搜索。但是电子邮件正文很长,我只想显示搜索文本的一小部分,例如,如果我搜索:

亲热

在以下文本中:

Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。 Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 Exceptioneur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est labourum。

结果应该是:

...aliquip ex ea commodo consequat。 Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur....

谢谢

【问题讨论】:

    标签: linq search text replace


    【解决方案1】:

    这样的事情应该可以完成:

    var query = from str in messages
      let index = str.IndexOf(search)
      where index > -1
      select str.Substring(Math.Max(0, index - radius), radius + Math.Min(radius, str.Length - index));
    

    messages 是您的电子邮件字符串列表,radius 是一个 int 值,用于描述您要在要查找的字符串之前和之后取多少个字符。请注意,此代码只会返回每封电子邮件中的第一个匹配项,而忽略其他匹配项。

    如果您可以使用辅助函数来计算正确的子字符串,一切都会变得更容易。

    Here你可以找到一个实现安全版本的string.substring的扩展方法,使得上面的linq代码看起来像:

    var query = from str in lst
      let index = str.IndexOf(search)
      where index > -1
      select str.SafeSubstring(index - radius, 2*radius);
    

    在我看来,阅读起来要简单得多

    编辑

    使用以下两种方法扩展字符串:

        public static List<int> IndexOfAll(this String str, string search)
        {
            List<int> lst = new List<int>();
            foreach (Match match in Regex.Matches(str,search))
            {
                lst.Add(match.Index);
            }
            return lst;
        }
    
        public static string SafeSubstring(this String str, int start, int n)
        {
            return str.Substring(Math.Max(start, 0), Math.Min(n, str.Length - start));
        }
    

    你可以用一个很好的形式得到所有的结果,使用

    var query = from str in lst
      let index = str.IndexOfAll(search)
      where index.Count>0
      select index.Select(x => str.SafeSubstring(x-radius, 2*radius));
    

    查询作为 IEnumerable

    【讨论】:

    • 我想通了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    相关资源
    最近更新 更多