如何将字符串及其状态保存到列表中?

How to save a string plus its state into List?

我在使用 EF Core 1.2 的 C# 中有以下代码,我正在读取文本区域的输入并检查每一行是否与我的模式之一匹配。 检查一行后,我试图设置一个状态,告诉我它是否匹配一种模式。

现在我想将这些行及其每个状态临时保存到一个列表中,这样我就可以将这个列表传递给我的视图,我想在视图中显示每个行及其状态 table。

我的问题是如何保存每一行及其状态?我考虑过使用字典,但我不确定这是否是解决我的问题的最佳方法。

using (StringReader reader = new StringReader(Request.Form["ExpressionTextarea"].ToString()))
{
    string line = string.Empty;

    do
    {
        line = reader.ReadLine();

        if (line != null)
        {
            string state = CheckStringLine(line);

            /**** HOW TO SAVE EACH LINE PLUS ITS STATE TEMPORARILY?
            //IDictionary<string, string> dictionary = new Dictionary<string, string>();
            //dictionary.Add(line, status);
            ****/
        }
    } while (line != null);

    //***PASSING MY LIST TO MY VIEW
    return View(MYLIST);
}

//Checks if line matches a pattern
public string CheckStringLine(string Line)
{          
    string state = "";
    //Pattern1: (Ein | Eine) A ist (ein | eine) B.
    string pattern1 = @"^(?<Artikel1>(Ein|Eine){1})\s{1}(?<Second>[A-Z]{1}[a-zäöüß]{1,})\s{1}ist\s{1}(?<Artikel2>(eine|ein){1})\s(?<Fourth>[A-Z]{1}[a-zäöüß]{1,})\.$";

    //Pattern2: (Ein | Eine) A (oder (ein | eine) B)+ ist (ein | eine) C.
    string pattern2 = @"^(?<First>(Ein|Eine){1})\s{1}(?<Second>[A-Z]{1}[a-zäöüß]{1,})(\s{1}oder\s{1}(?<OptionalArtikel>(ein|eine){1})\s{1}(?<OptionalBegriff>[A-Z]{1}[a-zäöüß]{1,}))+(\s{1})ist\s{1}(?<Third>(eine|ein){1})\s(?<Fourth>[A-Z]{1}[a-zäöüß]{1,})\.$";

    var match1 = Regex.Match(Line, pattern1);
    var match2 = Regex.Match(Line, pattern2);

    if (match1.Success)
    {
        state = "This Line is using pattern1";

        return state;
    }
    if (match2.Success)
    {
        state = "This Line is using pattern2";
        return state;
    }           

    state = "No matches";
    return state; 
}

使用 Dictionary 适用于需要 key/value 对的情况,我知道您只是想存储东西。另外,如果您想保留订单,那将行不通。

如果您不想为此创建自己的类型,最简单的方法是使用包含 TupleList

var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>(line, state));

然后,当您需要它们时,您可以从列表中获取元组并从 Item1 中获取行,从 Item2 中获取状态。

您可以使用任何内存中的数据结构来存储您的状态。 HashTable 会比其他数据结构快很多,但它不是通用的。您也可以使用通用的字典。