Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在排序列表中按键存储对象?_C#_Object_Sortedlist - Fatal编程技术网

C# 如何在排序列表中按键存储对象?

C# 如何在排序列表中按键存储对象?,c#,object,sortedlist,C#,Object,Sortedlist,我有两节课。 一个类是该类型的对象 公共类Taksi { 公共整数; 公共字符串品牌; 公共字符串FIO; 公共双里程; //我错过了接球和二传手 公共塔克西(整数纽纳姆、字符串纽兰、字符串纽菲奥、双里程) { this.brand=newBrand; this.FIO=newFio; 这个。英里数=英里数; this.num=newNum; } } 第二个类存储一个类似sortedList Park{get;}的sortedList 公共类分类列表:FileEvent,grid { 分类列表

我有两节课。 一个类是该类型的对象

公共类Taksi
{
公共整数;
公共字符串品牌;
公共字符串FIO;
公共双里程;
//我错过了接球和二传手
公共塔克西(整数纽纳姆、字符串纽兰、字符串纽菲奥、双里程)
{
this.brand=newBrand;
this.FIO=newFio;
这个。英里数=英里数;
this.num=newNum;
}
}
第二个类存储一个类似sortedList Park{get;}的sortedList

公共类分类列表:FileEvent,grid
{
分类列表公园{get;}
公共分类列表()
{
驻车=新分拣列表();
}
}
类sortedList FileEvent.scanFile(字符串路径文件)中的函数中 我用钥匙和出租车对象填写排序列表。 在此行中,Park.Add(Int32.Parse(dataArray[0]),newTaksi)

void FileEvent.scanFile(字符串路径文件)
{
Taksi newTaksi;
IEnumerable lines=Enumerable.Empty();
尝试
{
lines=File.ReadLines(路径文件);
}
捕获(例外e)
{
MessageBox.Show(“打开文件时出现异常:+e”);
}
foreach(行中的var行)
{
尝试
{
string[]dataArray=line.Split(“|”);
newTaksi=newTaksi(Int32.Parse(dataArray[0]),
dataArray[1],
dataArray[2],
Parse(dataArray[3]);
Park.Add(Int32.Parse(dataArray[0]),newTaksi);
}
捕获(例外e)
{
Show(“解析文件时出现异常:+e”);
}
}
}
**如何从排序列表中取回滑行对象和对象数据?***

使用
SortedList
而不是
SortedList
。如果您在此处指定了正确的类型,列表将知道它包含的对象的类型,并且您可以作为正确的类型访问它们

要从列表中获取taksi by编号,可以使用
TryGetValue
方法:

if(Park.TryGetValue(42, out Taksi myTaksi))
{
    // Number 42 was in the list and you can use it here as myTaksi
}
else
{
    // There is no taxi with number 42 in the list
}
如果确定列表中有某个数字,则可以使用方括号访问该数字:

Taksi no42 = Park[42];
要在列表中的所有对象上循环,请执行以下操作:

foreach(Taksi taksi in Park.Values)
{
    // Do something with taksi
}
foreach(var pair in Park)
{
    // pair.Key is the number
    // pair.Value is the Taksi object
}
或者,如果要访问对象及其在列表中添加的编号:

foreach(Taksi taksi in Park.Values)
{
    // Do something with taksi
}
foreach(var pair in Park)
{
    // pair.Key is the number
    // pair.Value is the Taksi object
}

是否要通过对象的
num
访问该对象?为什么要将列表声明为
,而不是
?为什么它必须是已排序的列表?字典对键/值对更有意义。在赋值时,我需要使用SortedList并从中按编号获取对象。我如何通过数字和数据从这个类中获取一个对象?例如,我想迭代对象forEach,但我不能这样做foreach(Taksi s in Park[1234]){MessageBox.Show(s.FIO.ToString());}````@NineBerry它起作用了,谢谢。