从对象列表中检索一个对象,但不是通过 index[],而是通过字段 [duplicate] 的名称

Retrieve one object from a list of objects, but not by index[], but by a name of a field [duplicate]

提问人:marcoqf73 提问时间:11/7/2023 最后编辑:marc_smarcoqf73 更新时间:11/7/2023 访问量:49

问:

最后,您可以找到类和 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; }
}
C# JSON 列表 对象 搜索

评论

3赞 John Wu 11/7/2023
使用 LINQ 时,这很简单。var item = connections.Single( x => x.name_connection == "Connection_A" );
0赞 Yong Shun 11/7/2023
LINQ 将是您最好的朋友。=) 否则,回到基本,使用 loop 迭代和检查每个元素。

答:

3赞 Fildor 11/7/2023 #1

如前所述,简单的解决方案是使用 LINQ

public static TestExtensions
{
    public static Connection? GetConnectionByName( this Test test, string name )
      => test.connections.FirstOrDefault( x => x.name_connection == name );
     // Consider string.Equals(a, b, StringComparison) , though
}

// usage
var item = test.GetConnectionByName("ConnectionA");

如果你需要这个非常高的频率,那么你可能想要建立一个更有效的查找:

var connectionByName = test.connections.ToDictionary(x => x.name_connection, x => x);
// ^^ Do this _once_ and store the dictionary.
//    Also consider using the overload that lets you specifiy string comparison for the keys
var connection = connectionByName["ConnectionA"];

尽管重复被标记,但我想保留这个答案,因为在重复中,我还没有看到解决性能方面的答案。