Files
SzmediTools/BoreholeExtract/KeywordMatcher.cs
2025-12-23 21:37:02 +08:00

47 lines
1.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
namespace BoreholeExtract
{
public class KeywordMatcher
{
// 缓存字典Key是枚举Value是用户配置的关键词列表
private readonly Dictionary<Identify, List<string>> _keywordMap;
// 构造函数:传入 ViewModel 中的数据
public KeywordMatcher(IEnumerable<CategoryWrapper> dashboardItems)
{
_keywordMap = new Dictionary<Identify, List<string>>();
foreach (var item in dashboardItems)
{
// 过滤掉空字符串,防止 txt.Contains("") 永远为 true
var validKeywords = item.Items
.Where(k => !string.IsNullOrWhiteSpace(k))
.ToList();
if (validKeywords.Count > 0)
{
_keywordMap[item.Id] = validKeywords;
}
}
}
/// <summary>
/// 判断文本是否包含该 ID 下的任意一个关键词
/// </summary>
public bool IsMatch(Identify id, string text)
{
if (string.IsNullOrEmpty(text)) return false;
// 如果配置里没有这个 ID直接返回 false
if (!_keywordMap.TryGetValue(id, out var keywords)) return false;
// 核心逻辑:只要包含任意一个关键词,就返回 true
// StringComparison.OrdinalIgnoreCase 可以忽略大小写(可选)
return keywords.Any(k => text.Contains(k, StringComparison.OrdinalIgnoreCase));
}
}
}