且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两个数组中寻找共同的元素

更新时间:2022-12-09 19:09:17

您在处理一个多到多的关系在这里。结果
如果它是一个数据库,这意味着你会放在3个表:

You're dealing with a many-to-many relationship here.
If it were a database that means you'd put in 3 tables:

1. People
2. Colors
3. Link table between 1 and 2

我建议你要么通过利用数据库​​解决问题或者数据库在Delphi模拟的东西,就像它。

I suggest you either fix the problem by utilizing a database or model the thing in Delphi just like it where a database.

用Delphi结构结果
此外 ShortString短他们已经过时,有超过longstrings零收益停止使用。结果
使用3个表意味着您可以迅速得到人们每种颜色和颜色每人列表。

Using Delphi structures
Furthermore stop using shortstring They are outdated and have zero benefits over longstrings.
Using 3 tables means you can quickly get a list of people per color and colors per person.

下面是它如何工作:

TPerson = record
  name: string;
  other_data....
end;

TPeople = array of TPerson;

TFavColor = record
  name: string;
  other_data....
end;

TFavColors = array of TFavColor;

TPersonColor = record
  PersonIndex: Cardinal;  <<-- index into the TPeople array
  ColorIndex: Cardinal;   <<-- index into the TFavColors array
end;

TPersonColors = array of TPersonColor;

现在你可以遍历所有的TPersonColors阵列来提取数据。

Now you can just loop over the TPersonColors array to extract your data.

使用数据库结果
在SQL因为你的数据编制索引,将会变​​得更快(外键都(应该是)永远索引)。

Using a database
In SQL it would be even faster because your data is indexed (foreign key are (should be) always indexed).

SQL语句中看到所有的人,像蓝色和红色会是什么样子(这里使用MySQL的语法):

The SQL statement the see all people that like blue and red would look like (using MySQL syntax here):

SELECT p.name  
FROM person p
INNER JOIN personcolor pc ON (pc.person_id = p.id)
INNER JOIN color c1 ON (pc.color_id = c1.id)
INNER JOIN color c2 ON (pc.color_id = c2.id)
WHERE c1.name = 'red' AND c2.name = 'blue'
GROUP BY p.id <<-- eliminate duplicates (not sure it's needed)

用Delphi其琐碎的数据库链接到您的应用程序。结果
所以这是我推荐的路线。

Using Delphi its trivial to link a database to your app.
So that's the route I'd recommend.