Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   duda basica. linq con spring4d (https://www.clubdelphi.com/foros/showthread.php?t=97965)

alejandro.laord 14-01-2026 15:48:03

duda basica. linq con spring4d
 
Alguien sabe cómo hacer select, map o equivalente en spring4d, sé que haciendo un for.. in.. lo haría.
Estoy haciendo pruebas y no consigo dar con el tema.
Adjunto ejemplo:

Código Delphi [-]
program Project1;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils, Spring, Spring.Collections;

type
  TProduct = class
  public
    Name: string;
    Category: string;
    Price: Double;
    InStock: Integer;
    constructor Create(const AName, ACategory: string; APrice: Double;
      AInStock: Integer);
  end;

constructor TProduct.Create(const AName, ACategory: string; APrice: Double;
  AInStock: Integer);
begin
  Name := AName;
  Category := ACategory;
  Price := APrice;
  InStock := AInStock;
end;

var
  Products: IList;
  Nombres: IEnumerable<string>;

begin
  try
    Products := TCollections.CreateObjectList(True);
    Products.AddRange([TProduct.Create('artilugio', 'cacharro', 192.43, 3),
      TProduct.Create('cacharro', 'electrónica', 13.65, 10),
      TProduct.Create('pongo', 'cacharro', 52.22, 0), TProduct.Create('cosa',
      'electrónica', 11.33, 5), TProduct.Create('trasto', 'cacharro',
      43.44, 1)]);
    Writeln('Buscando nombres de electronica...');
    // Usando Map en lugar de select
    Nombres := Products.Where(
      function(const p: TProduct): Boolean
      begin
        Result := p.Category = 'electrónica';
      end).Map<string>(
      function(const p: TProduct): string
      begin
        Result := p.Name;
      end);
    for var s in Nombres do
      Writeln('Producto: ' + s);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;

end.

Casimiro Noteví 14-01-2026 16:28:29

Código Delphi [-]
program Project1;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Spring,
  Spring.Collections;

type
  TProduct = class
  public
    Name: string;
    Category: string;
    Price: Double;
    InStock: Integer;
    
    constructor Create(const AName, ACategory: string; APrice: Double; AInStock: Integer);
  end;

constructor TProduct.Create(const AName, ACategory: string; APrice: Double; AInStock: Integer);
begin
  Name := AName;
  Category := ACategory;
  Price := APrice;
  InStock := AInStock;
end;

var
  Products: IList;
  Nombres: IEnumerable<string>;

begin
  try
    Products := TCollections.CreateObjectList(True);
    
    Products.AddRange([
      TProduct.Create('artilugio', 'cacharro', 192.43, 3),
      TProduct.Create('cacharro', 'electrónica', 13.65, 10),
      TProduct.Create('pongo', 'cacharro', 52.22, 0),
      TProduct.Create('cosa', 'electrónica', 11.33, 5),
      TProduct.Create('trasto', 'cacharro', 43.44, 1)
    ]);

    Writeln('Buscando nombres de electronica...');
    
    // Usando Map en lugar de Select
    Nombres := Products
      .Where(function(const p: TProduct): Boolean
        begin
          Result := p.Category = 'electrónica';
        end)
      .Map<string>(function(const p: TProduct): string
        begin
          Result := p.Name;
        end);

    for var s in Nombres do
      Writeln('Producto: ' + s);
      
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  
  Readln;
end.

alejandro.laord 14-01-2026 17:05:36

Funciona
 
Gracias, he conseguido hacer una versión que sí funciona con select.


Código Delphi [-]
program Project1;

{$APPTYPE CONSOLE}
{$R *.res}
uses
  System.SysUtils,
  Spring.Collections,
  Spring;

type
  TProduct = class
  public
    Name: string;
    Category: string;
    Price: Double;
    InStock: Integer;
    constructor Create(const AName, ACategory: string; APrice: Double; AInStock: Integer);
  end;

{ TProduct }
constructor TProduct.Create(const AName, ACategory: string; APrice: Double;
  AInStock: Integer);
begin
  Name := AName;
  Category := ACategory;
  Price := APrice;
  InStock := AInStock;
end;

procedure ver(Lista : IEnumerable);
begin
  for var pProd in Lista  do
  begin
    Writeln('-----------------');
    writeln('Nombre producto: ' + pProd.Name);
    writeln('Categoría producto: ' + pprod.Category);
    Writeln('Precio producto: ' + CurrToStr(pprod.price));
    Writeln('Stock producto: ' + IntToStr(pProd.InStock));
    Writeln('-----------------');
  end;
  Readln;
end;

var
  Products : IList;

begin
  try
    //Writeln();
    Products := TCollections.CreateObjectList(true);
    (*Cargar los datos*)
    Products.AddRange([
      TProduct.Create('artilugio', 'cacharro', 192.43, 3),
      TProduct.Create('cacharro', 'electrónica', 13.65, 10),
      TProduct.Create('pongo', 'cacharro', 52.22, 0),
      TProduct.Create('cosa', 'electrónica', 11.33, 5),
      TProduct.Create('trasto', 'cacharro', 43.44, 1)
    ]);
    Writeln('PRODUCTOS EN ALMACÉN');
    ver(Products);
    (*Filtrar: Productos con precio superior a 50.00*)
    Writeln('PRODUCTOS CAROS (precio > 50)');
    var Caros := (Products.Where(
      function (const P:TProduct):boolean
      begin
        Result := (P.Price > 50);
      end));
    ver(Caros);
    (*Proyectar: Lista con nombres de productos de categoría "Electrónica"*)
    Writeln('NOMBRES DE PRODUCTOS DE ELECTRÓNICA:');
    Writeln('------------------------------------');
    var Nombres := Products
        .Where(function(const P: TProduct): Boolean
               begin
                 Result := P.Category = 'electrónica';
               end);
    Nombres.ForEach(procedure(const n:TProduct)
    begin
      Writeln('• ' + n.Name);
    end);
    Writeln('Total productos de electrónica: ' + Nombres.Count.ToString);
    Readln;
    (*Ejercicio 3. Sumar todos los stocks y dar la cifra de inventario*)
    var cTotal := TEnumerable.Select(
      Products,
      function(const P: TProduct): currency
      begin
        Result := p.Price * p.InStock;
      end).Sum; // Luego sumamos todos esos subtotales
    Writeln('Total valoración de stock: ' + CurrToStr(cTotal));
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.


La franja horaria es GMT +2. Ahora son las 06:38:20.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi