首页 > 解决方案 > 如何检查一个字符串是否匹配多个字符串并根据匹配返回值

问题描述

如果标题没有多大意义,请道歉,英语不是我的母语。

我正在尝试做的事情: 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% 准确的键。密钥包含在字符串中,但字符串中有额外的数据。

我希望我想做的事情不会太混乱。

标签: c#

解决方案


尝试以下 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"}
        };
    }

}

推荐阅读