使用特定条件将内容从list1复制到list2 [英] copy content from list1 to list2 with specific criteria

查看:155
本文介绍了使用特定条件将内容从list1复制到list2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个这样定义的泛型列表:

if i have two generics list so defined:

type
  pMyList = record
    a, b: integer;
    c: string; 
  end;
  TMyList = TList<pMyList>;

var
  list1, list2: TMyList;

有一些函数将内容从列表(es:list1)复制到其他列表(es:list2) )仅在某些领域符合条件时?例如,我想从list1复制list2的所有记录,其中a是相同的值,例如1。
结果是list2我拥有list1的所有记录,其中a = 1,不包括a是值的所有其他记录。不同于1。
真诚地我已经解决了这样做的问题:

there is some function copy content from a list (es: list1) to other list (es: list2) only if some field respect condition? For example, i want copy in list2 from list1 all record where a is same value for example 1. Result is that in list2 i have all record of list1 where a = 1, excluding all other record where a is a value different from 1. Sincerly i have solved problem doing so:

for iIndex := 0 to Pred(list1.Count) do
  if list1[iIndex].a = myvalue then list2.Add(list1[iIndex]);

,但想知道是否有更特定的功能来执行此操作,例如使用某些功能德尔福
非常感谢。

but wanted to know if there is something more specific for to do this operation, using for example some function of delphi. Thanks again very much.

推荐答案

不幸的是,由于Delphi缺少使用Collections或Spring的泛型列表的lambda表达式,框架可以使源代码更长一些。另外,有些人不喜欢使用匿名方法,因为它们的语法非常繁琐。

Unfortunately because Delphi is lacking lambda expressions using Collections or the generic lists from the Spring framework can make the source code a bit longer. Also some people don't like using anonymous methods because their syntax is so cumbersome. But that is a matter of taste imho.

有了Collections,您的示例将如下所示:

With Collections your example would look like this:

list2.AddAll(list1.Where(
  function(value: pMyList): Boolean
  begin
    Result := value.a = myvalue;
  end));

请记住,上述两个泛型列表实现都在实现接口,并且大多数方法都在使用它们。在上面的示例中,这并不重要,因为您没有直接传递list1。

Keep in mind that both mentioned generic lists implementations are implementing interfaces and most of the methods are operating with them. In the example above that does not matter because you are not passing list1 directly. Otherwise it would be freed after.

使用单个示例,使用它们的好处可能并不明显,但是当您进行大量操作,过滤数据并将它们放入其他操作时列表等等,它变得更加容易,您无需编写许多其他方法即可执行这些操作。但是正如我说的那样,很多delphi开发人员似乎都不喜欢这种语法和编写代码的方式。

With that single example the benefit of using them might not be clear but when you do lots of operations, filtering data, putting them into other lists and much more it gets easier and you don't have to write lots of extra methods to do these operations. But as I said it's a matter of taste, many delphi developers seem to not like that syntax and way to write code.

这篇关于使用特定条件将内容从list1复制到list2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆