es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo comparar dos listas en memoria en APEX

Tengo dos listas en memoria (ver imagen a continuación). Quiero calcular el valor de la columna TotalSellPrice para cada fila.

Basándome en el Libro y la Categoría, necesito calcular la columna TotalSellPrice para BookCategory. Sigo los siguientes pasos, ¿hay algo más eficiente que eso?

Decimal totalSellPrice=0;

para (lista de BookCategory)
{
totalSellPrice=0;
para (lista de SellBookCategoryPrice)
{
si(BookCategory.Book==SellBookCategoryPrice.Book && BookCategory.Category==SellBookCategoryPrice.Category)
{
totalSellPrice+=SellBookCategoryPrice.Price;
}
}
//Prepara la lista de BookCategory con el nuevo totalSellPrice
}

//actualiza la nueva lista preparada de BookCategory

Tags:  ,

Answer

  1. Avatar for davy.ai

    Hay una manera más eficiente de calcular TotalSellPrice sin necesidad de bucles anidados. Se puede usar un Map para almacenar los valores de SellBookCategoryPrice con una clave compuesta de Book y Category. Luego se puede recorrer la lista BookCategory y recuperar el valor de SellBookCategoryPrice del mapa usando la clave compuesta. Aquí está el fragmento de código:

    Decimal totalSellPrice=0;
    Map<string, decimal=""> sellPriceMap = new Map<string, decimal="">();
    for(SellBookCategoryPrice sbcp : SellBookCategoryPrice) {
        String key = sbcp.Book + '|' + sbcp.Category;
        if(!sellPriceMap.containsKey(key)) {
            sellPriceMap.put(key, sbcp.Price);
        } else {
            Decimal existingPrice = sellPriceMap.get(key);
            sellPriceMap.put(key, existingPrice + sbcp.Price);
        }
    }
    
    for(BookCategory bc : BookCategory) {
        String key = bc.Book + '|' + bc.Category;
        if(sellPriceMap.containsKey(key)) {
            bc.TotalSellPrice = sellPriceMap.get(key);
        }
    }
    

    Con este código, se puede evitar el bucle anidado y calcular TotalSellPrice de manera más eficiente.</string,></string,>

Comments are closed.