如何在c#中创建列表并查找值?
本文关键字:查找 列表 创建 | 更新日期: 2023-09-27 18:04:15
我想在c#中实现某种查找,但我不确定如何做到这一点。
我有一个变量,它的值可以在0到9之间。对于每个变量,都有一个文本字符串。
我想我需要列一个清单。
一个关于如何访问列表以及如何填充列表的简单示例将不胜感激。
我试了如下:
public static class RefData
{
public static Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(0, "This Text");
dict.Add(3, "That Text");
dict.Add(4, "More Text");
}
,但它给出一个错误消息,说"不能解析符号字典的行与字典。"div添加
这是对更新后的问题的回答。当前代码的问题是,您试图执行语句,而不将它们放在方法、属性、构造函数等内部。你不能这么做。这里有两个明显的选择。首先,您可以使用一个方法来构建字典:
public static class RefData
{
private static readonly Dictionary<int, string> dict = BuildDictionary();
private static Dictionary<int, string> BuildDictioary()
{
Dictionary<int, string> ret = new Dictionary<int, string>();
ret.Add(0, "This Text");
ret.Add(3, "That Text");
ret.Add(4, "More Text");
return ret;
}
}
另一个是使用集合初始化器如果你使用c# 3或更高版本:
public static class RefData
{
private static readonly Dictionary<int, string> dict =
new Dictionary<int, string>
{
{ 0, "This Text" },
{ 3, "That Text" },
{ 4, "More Text" }
};
}
注意,在这两种情况下,我是如何将变量设置为私有和只读的。您几乎不应该公开公开字段——尤其是可变字段。您可能希望提供适当的方法,使对字典起作用—并且记住Dictionary
是不是线程安全的。
您试图将代码放入类定义中。您需要在方法或静态构造函数中移动dict.Add()调用。比如:
public static class RefData
{
public static Dictionary<int, string> dict = new Dictionary<int, string>();
static Refdata() //this could also be: public static void PopulateDictionary()
{
dict.Add(0, "This Text");
dict.Add(3, "That Text");
dict.Add(4, "More Text");
}
}
你可以这样做,如果你想用默认数据填充它,我想,你总是可以添加或删除键从你的代码的其他部分,因为它是一个公共静态成员。
通用字典。比如:
Dictionary<int, string> dict = new Dictionary<int, string>()
第一个类型,int是键。每个键必须是唯一的,并且有一个字符串值。
如果你做了这样的事情:
dict.Add(0, "This Text");
dict.Add(3, "That Text");
dict.Add(4, "More Text");
你可以像这样查找值:
string value = dict[3]; //returns "That Text"
如果键已经存在于字典中,则添加将失败。就像你不能做两次一样:
dict.Add(3, "That Text");
dict.Add(3, "More Text");
如前所述,键(在本例中是int)必须是唯一的。可以通过
重新赋值 dict[3] = "New Text"
泛型字典的伟大之处在于,它可以保存任何你想要的类型!字典的定义是Dictionary<Tkey, TValue>
,您可以指定类型,并且可以将它们设置为您想要的任何类型
可以在System.Collections.Generic
中使用Dictionary
类
Dictionary<byte, string> dct = new Dictionary<byte, string>();
你可以像这样给字典添加值
dct.Add(0, "Some Value");
你可以像这样访问字典中的值
string val = dct[0];
I have a variable that can have a value of between 0 and 9. For each variable there will be a text string that goes with it.
这意味着你需要一本字典。你可以在。net中使用许多专门的字典。但我建议使用:
Dictionary<int, string> list = new Dictionary<int, string>();
检查列表是否已经包含一些内容,只需使用:
list.ContainsKey(someIntHere);
获取指定键的字符串值,只需使用:
string value = list[key];
字典类在这里是你的朋友。
。
var textByNumber = new Dictionary<int, string>();
textByNumber[0] = "Alice";
textByNumber[1] = "Bob";
要检索一个值,您可以执行:
var text = textByNumber[1];