c# - 如何检查一个字符串是否匹配多个字符串并根据匹配返回值
问题描述
如果标题没有多大意义,请道歉,英语不是我的母语。
我正在尝试做的事情: 1. 我有一个字符串列表 2. 我想根据另一个字符串列表检查每个字符串 3. 根据它们包含的字符串,输出会有所不同
在代码中,它看起来像这样:
public static Hashtable Matches = new Hashtable
{
{"first_match", "One"},
{"second_match", "Two"},
{"third_match", "Three"},
{"fourth_match", "Four!"},
{"fifth_match", "Five"}
};
现在,我有一个这样的字符串列表:
001_first_match
010_second_match
011_third_match
我想检查列表中的每个字符串是否存在于哈希表中(或者可能是其他适合这种情况的数据类型,建议赞赏),并在此基础上获取键的值。
例如:是在带有键001_first_match
的哈希表中。first_match
如果找到,那么我想取它的One
价值并使用它。
我不能使用ContainsKey
,因为字符串列表不是 100% 准确的键。密钥包含在字符串中,但字符串中有额外的数据。
我希望我想做的事情不会太混乱。
解决方案
尝试以下 linq :
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication58
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
string[] inputs = { "001_first_match", "010_second_match", "011_third_match" };
foreach (string input in inputs)
{
var results = Matches.Keys.Cast<string>().Where(x => input.Contains(x)).FirstOrDefault();
Console.WriteLine("Input '{0}' found in HashTable : {1}", input, (results == null) ? "False" : "True, key = '" + results + "', Value = '" + Matches[results] + "'");
}
Console.ReadLine();
}
public static Hashtable Matches = new Hashtable
{
{"first_match", "One"},
{"second_match", "Two"},
{"third_match", "Three"},
{"fourth_match", "Four!"},
{"fifth_match", "Five"}
};
}
}
推荐阅读
- php - 在隐藏页面上处理 PHP 表单,但保持在同一页面上。没有 Ajax,只有纯 php(项目)
- android - 在片段中启动 recyclerview 时出现错误 findViewById
- python - 如何创建一个入口规则,源是 boto3 中的 sg
- python - 如何使用 python 从网站截取屏幕截图?
- java - Icecast 直播将非静音部分提取到单个文件中
- c# - 从 AJAX JSON 提交到 SQL Server --> Web 方法
- postman - 来自 JSON 的请求正文变量不接受整数值
- python - 如何每次将列表附加到 CSV 文件的新列?
- java - 从另一个类访问函数
- python - 如何使用 Python 在 Selinum 中单击给定 Xpath 的图像?