将项目添加到 TList 中的高效准确方法

本文关键字:高效 方法 项目 添加 TList | 更新日期: 2023-09-27 18:33:24

我有 2 个列表,这些列表的实体有一些 ID 例如

Client.ID,其中 ID 是客户端的属性,

那么我有PopulationClient.ID,其中 ID 是类 PopulationClient 的属性。所以我有两个列表

TList<Client> clients = clientsHelper.GetAllClients();
TList<PopulationClient> populationClients = populationHelper.GetAllPopulationClients();

所以我有一个临时列表

TList<Client> temp_list = new TList<Client>();

所以我遇到的问题是高效和正确地做到这一点。这就是我尝试过的..但我没有得到正确的结果

foreach(PopulationClient pClients in populationClients)
{
    foreach(Client client in clients)
     {
         if(pClients.ID != client.ID  &&  !InTempList(temp_list, pClients.ID))
         {
             temp_list.Add(client);
         }
     }
}
public bool InTempList(TList<Client> c, int id)
{
    bool IsInList = false;
    foreach(Client client in c)
    {
        if(client.ID == id)
        {
              IsInList = true;
        }
    }    
   return IsInList;
}

因此,当我试图正确地做到这一点时,我无法想出一个好的方法,这并没有返回正确的数据,因为在顶部第一个循环中的语句中,在某些时候一个或多个与另一个不同,所以它无论如何都会添加它。您认为我应该在这里检查哪些约束,以便我最终只得到一个在人口客户端中而不是在客户端中的客户端列表?

例如,人口客户端

将有 4 个客户端和客户端 2,这 2 个也在人口客户端中,但我需要获取不在客户端中的人口客户端列表。

一个帮助或指示将不胜感激。

将项目添加到 TList 中的高效准确方法

首先,让我们专注于获得正确的结果,然后我们将进行优化。

考虑一下你的嵌套循环:你会得到太多的积极因素,因为在大多数(pclient,client(对中,ID不匹配。我想你想像这样编码:

foreach(PopulationClient pClients in populationClients)
{
     if(!InTempList(clients, pClients.ID) && !InTempList(temp_list, pClients.ID))
     {
         temp_list.Add(client);
     }
}

现在,对于该代码的效率:InTempList使用线性搜索列表。这是没有效率的 - 考虑使用搜索速度更快的结构,例如哈希集。

如果我了解您要查找的内容,这里有一种方法可以使用 LINQ ...

tempList = populationList.Where(p => !clientList.Any(p2 => p2.ID == p.ID));

只是为了提供另一个基于 LINQ 的答案...我认为您的意图是根据"客户端"(从 GetAllClients 返回(中未显示在 populationClients 集合中的所有项目(基于"ID"值(填充 tempList。

如果是这种情况,那么我将假设 populationClients 足够大,可以保证进行基于哈希的外观(例如,如果少于 10 个项目,线性扫描可能没什么大不了的(。

因此,我们想要 populationClients 集合中所有 ID 值的快速查找版本:

var populationClientIDs = populationClients.Select(pc => pc.ID);
var populationClientIDHash = new HashSet(populationClientIDs);

现在我们有了要在快速查找数据结构中忽略的 ID 值,我们可以将其用作客户端的过滤器:

var filteredClients = clients.Where(c => populationClientIDHash.Contains(c.ID) == false);

根据使用情况/需要,您可以从"filteredClients"填充tempList,或者执行ToList或其他操作。