copy content from list1 to list2 with specific criteria

℡╲_俬逩灬. 提交于 2019-12-10 19:09:24

问题


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.


回答1:


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.




回答2:


What about this?

class procedure TCollectionUtils.CopyItems<T> (List1, List2 : TList <T>; Pred : TFunc <T, Boolean>);
var
 Item : T;
begin
for Item in List1 do
  if Pred (Item) then
    List2.Add (Item);
end;

The call would look like this:

TCollectionUtils.CopyItems <pMyList> (list1, list2,
  function (Item : pMyList) : Boolean
  begin
  Result := (pMyList.a = 1);
  end);

(no Delphi here right now)



来源:https://stackoverflow.com/questions/8246378/copy-content-from-list1-to-list2-with-specific-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!