使用List <KeyValuePair>存储键和值

Jos*_*osh 2 c#

我仍在努力理解,KeyValuePairs但我相信这个想法应该有效.在我的下面的代码中,它搜索一个大字符串并提取2个子字符串.一个子字符串(请记住引号之间的值不同)就像是Identity="EDN\username"另一个子字符串之类的东西FrameworkSiteID="Desoto" 所以我想在将它们添加到List之前将这些字符串组合在一起但这里是我的问题..下面的登录字符串是一个我需要在SQL语句中使用的唯一字符串字段来选择SQLServer和中的记录 framew中的字符串是我需要与登录字符串(以及来自SQLServer的所有数据列和行)排列的字符串,当我将其输出到文本文件时.我应该使登录字符串KEYS和framew字符串VALUES?如果是这样我该怎么做?希望有道理.我可以进一步解释是否需要

Regex reg = new Regex("Identity=\"[^\"]*\"");
Regex reg1 = new Regex("FrameworkSiteID=\"[^\"]*\"");

foreach (FileInfo file in Files)
{
    string line = "";
    using (StreamReader sr = new StreamReader(file.FullName))
    {
        while (!String.IsNullOrEmpty(line = sr.ReadLine()))
        {
            if (line.ToUpper().Contains("IDENTITY="))
            {
                string login = reg.Match(line).Groups[0].Value;
                string framew = reg1.Match(line).Groups[0].Value; //added
                IdentityLines.Add(new KeyValuePair<string, string>(file.Name, login + " " + framew));
                    //This is probably not what I need
            }


            else
            {
                IdentityLines.Add(new KeyValuePair<string, string>(file.Name, "NO LOGIN"));
            }
        }
Run Code Online (Sandbox Code Playgroud)

Jak*_*ake 5

KeyValuePair<TKey,TValue>Dictionary<TKey,TValue>班级使用的结构.不是保留KeyValuePair<TKey,TValue>对象列表,而是创建一个Dictionary<TKey,TValue>并向其添加键/值.

例:

Dictionary<string,string> identityLines = new Dictionary<string,string>();
foreach (FileInfo file in Files)
{
    string line = "";
    using (StreamReader sr = new StreamReader(file.FullName))
    {
        while (!String.IsNullOrEmpty(line = sr.ReadLine()))
        {
            if (line.ToUpper().Contains("IDENTITY="))
            {
                string login = reg.Match(line).Groups[0].Value;
                string framew = reg1.Match(line).Groups[0].Value; //added
                identityLines.Add(login, framew);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将在登录和framews之间创建关联.如果要按文件对这些进行排序,可以创建一个Dictionary<string, Dictionary<string,string>>并将每个identityLines字典与特定文件名相关联.请注意,该Dictionary<TKey, TValue>类型的键值是唯一的 - 如果您尝试添加已添加的键,则会出现错误.