Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy content from list1 to list2 with specific criteria

if i have two generics list so defined:

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

var
  list1, list2: TMyList;

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.

like image 944
Marcello Impastato Avatar asked Dec 21 '25 01:12

Marcello Impastato


1 Answers

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.

With Collections your example would look like this:

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

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.

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.

like image 105
Stefan Glienke Avatar answered Dec 24 '25 12:12

Stefan Glienke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!