最后你可以找到类和 Json 文件。
如何从对象列表中检索一个对象,而不是通过索引
[]
而是通过字段名称?我需要检索完整的对象。
反序列化 Json 文件后,我有一个连接列表:
// List of connections are in m_ListTest
Test m_listTest = new Test();
此时,我想通过传递连接名称来从该列表中检索特定元素
m_listTest.connections.name_connection == "Connection_A"
// Not by index
var ritorna_elemento_del_indice_selezionato_1 = m_listTest.connections[0];
// But by Name
var ritorna_elemento_del_indice_selezionato_2 = m_listTest.connections.name_connection == "Connection_A";
Json 文件:
{
"connections": [
{
"name_connection": "Connection_A",
"imap_host": "imap.mail.com",
"imap_user": "[email protected]",
"imap_pass": "aaaaaaaaaa",
"imap_SSL_TLS": 993,
"folder_to_open": [ "folder_A_/subfolder1", "folder_A_/subfolder2" ],
"excluded_emails": [ "[email protected]", "[email protected]", "[email protected]" ]
},
{
"name_connection": "Connection_B",
"imap_host": "imap.mail.com",
"imap_user": "[email protected]",
"imap_pass": "bbbbbbb",
"imap_SSL_TLS": 993,
"folder_to_open": [ "folder_B_/subfolder1", "folder_B_/subfolder2" ],
"excluded_emails": [ "[email protected]", "[email protected]", "[email protected]" ]
}
]
}
这是班级:
public class Test
{
public Connection[] connections { get; set; }
}
public class Connection
{
public string name_connection { get; set; }
public string imap_host { get; set; }
public string imap_user { get; set; }
public string imap_pass { get; set; }
public int imap_SSL_TLS { get; set; }
public string[] folder_to_open { get; set; }
public string[] excluded_emails { get; set; }
}
如前所述,简单的解决方案是使用 LINQ
public static TestExtensions
{
public static Connection? GetConnectionByName( this Test test, string name )
=> test.connections.FirstOrDefault( x => x.name_connection == name );
}
// usage
var item = test.GetConnectionByName("ConnectionA");
如果您需要以非常高的频率,那么您可能需要构建更有效的查找:
var connectionByName = test.connections.ToDictionary(x => x.name_connection, x => x);
// ^^ Do this _once_ and store the dictionary.
var connection = connectionByName["ConnectionA"];