简体   繁体   English

C# 在列表中动态创建字典列表并填充/检索值

[英]C# Make List of dictionaries in List dynamically and populate/retrieve values

I read a parameters file who has sections and under each section a parameter, an equal sign and a value.我读了一个参数文件,它有几个部分,每个部分下都有一个参数、一个等号和一个值。 For example:例如:

[users]
Nick=twelve
John=eleven
Mary=twentynine

[stations]
pc1=on
pc2=on
pc3=off
pc4=off

[grades]
a=distinction
b=good
c=pass

etc..

I am trying to make a List of Dictionaries, since by definition I do not have repetitions of parameters' names (for example, parameter "pc1" can appear in any, but only one, section - for example above, it exists in section "[stations]" etc.) and populate as well as retrieve the data.我正在尝试制作一个字典列表,因为根据定义,我没有重复的参数名称(例如,参数“pc1”可以出现在任何部分,但只能出现在一个部分中 - 例如上面,它存在于部分“ [站]”等)并填充和检索数据。

For example:例如:

MyList.Add(new Dictionary<string, string>()); // "users" - how do I name the dictionary dynamically, as I read the section name?
MyList.Add(new Dictionary<string, string>()); // "stations"

etc.等等

The objective I am trying to achieve, is to query the list, knowing the dictionary name and the key, and retrieve the value if the key exists.我试图实现的目标是查询列表,知道字典名称和键,如果键存在则检索值。

string JohnCode = MyList("users", "John")    //if key "John" exists in users Dictionary

NOTE: I do NOT know beforehand the names and how many sections are in my data.注意:我事先不知道名称以及我的数据中有多少部分。 All I know is that sections are in brackets, ie [namehere] and then always follow key-value pairs as above.. Assume every key-pair is a string.我所知道的是,部分在括号中,即 [namehere] 然后总是遵循上面的键值对。假设每个键对都是一个字符串。

Can you help me?你能帮助我吗? Thank you in advance.先感谢您。

I'm going to assume that your section and keys only allow certain characters.我将假设您的部分和键只允许某些字符。 Use that to your advantage and make a single Dictionary where the Key is the combination of the file's section and key.使用它对您有利并制作一个字典,其中键是文件部分和键的组合。

In this example, I'll use a pipe |在本例中,我将使用 pipe | to separate the segments in the Dictionary Key.分隔字典键中的段。

var data = new Dictionary<string, string>();
data.Add("users|Nick", "twelve");
//...
data.Add("stations|pc1", "on");
//...
data.Add("grades|a", "distinction");
//...

Now when you want to lookup an entry, you lookup by both section and key ("users|Nick").现在,当您要查找条目时,您可以按部分和键(“users|Nick”)查找。

This however requires all entries to be part of a section.然而,这要求所有条目都是一个部分的一部分。 If you need to, as you read the ini file you can keep a seperate list of the section names to assist you with doing lookups later.如果需要,当您阅读 ini 文件时,您可以保留一个单独的部分名称列表,以帮助您稍后进行查找。


While it's a bit more expensive than having individual Dictionaries per section, you can still query the data.虽然它比每个部分都有单独的字典要贵一些,但您仍然可以查询数据。

To get a distinct list of all sections:要获得所有部分的不同列表:

var sectionNames = data
    .Select(x => x.Key.Split('|')[0])
    .Distinct();

To get all entries in a section获取部分中的所有条目

var sectionName = "users";
var entriesInUsersSection = data
    .Where(x => x.Key.StartsWith(sectionName + "|"));

And more Linq manipulations are possible.并且可以进行更多 Linq 操作。

If you want a unique Dictionary<string, string> to store the values of each section as indicated in the comments on another answer, is there any reason you have to use a List<Dictionary<string, string>> ?如果您想要一个唯一的Dictionary<string, string>来存储每个部分的值,如另一个答案的评论中所示,是否有任何理由必须使用List<Dictionary<string, string>> Because it seems like you'd be able to solve this with a Dictionary<string, Dictionary<string, string>> .因为您似乎可以使用Dictionary<string, Dictionary<string, string>>来解决这个问题。

The key of the Dictionary<string, Dictionary<string, string>> is the section name. Dictionary<string, Dictionary<string, string>>key是节名。 The value would be a Dictionary<string, string> containing the values under that section.value将是Dictionary<string, string>包含该部分下的值。

Dictionary<string, Dictionary<string, string>> sections = 
    new Dictionary<string, Dictionary<string, string>>();

sections.Add("users", new Dictionary<string, string>>());
sections.Add("stations", new Dictionary<string, string>>());
sections["users"].Add("Nick", "twelve");
sections["stations"].Add("pc1", "on"); 

string Nick = sections["users"]["Nick"]; // Nick = "twelve"
string pc1 = sections["stations"]["pc1"]; // pc1 = "on"

You could use an extension method to Dictionary<string, Dictionary<string, string>> to handle searching safely.您可以使用Dictionary<string, Dictionary<string, string>>扩展方法来安全地处理搜索。 For example:例如:

public static class IniExtensions
{
    public static bool TryGetSectionValue(
        this Dictionary<string, Dictionary<string, string>> src,
        string section, string key, out string value)
    {
        value = null;
        if (src.TryGetValue(section, out Dictionary<string, string> sectionValues))
        {
            return sectionValues.TryGetValue(key, out value);
        }
        return false;
    }
}

Dictionary<string, Dictionary<string, string>> sections = 
    new Dictionary<string, Dictionary<string, string>>();

sections.Add("users", new Dictionary<string, string>>());
sections.Add("stations", new Dictionary<string, string>>());
sections["users"].Add("Nick", "twelve");
sections["stations"].Add("pc1", "on"); 

// This returns true, and the Nick variable will have a value of "twelve"
sections.TryGetSectionValue("users", "Nick", out string Nick);

// this returns false, and the value variable has a value of null
sections.TryGetSectionValue("No Section", "Nick", out string value);

// this returns false, and the John variable has a value of null
sections.TryGetSectionValue("users", "John", out string John);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM