user8670136
user8670136

Reputation:

How to get one result from a list in another method?

Hi all I'm new to C#.

I try to return a result "totalAmount" from my method called "GetAllKschl". In this method I returned a list with "KSCHL, KSCHLData, price, pieces und totalPrice".

So in my new method I need the total amount of all "totalPrice" together.

first method:

public List<Result> GetAllKschl(string fileNameResult, string fileNameData)
{
    List<Result> listResult = new List<Result>();
    docResult.Load(fileNameResult);
    docData.Load(fileNameData);

    var resultList = docResult.SelectNodes("//root/CalculationLogCompact/CalculationLogRowCompact");

    foreach (XmlNode nextText in resultList)
    {
        XmlNode KSCHL = nextText.SelectSingleNode("KSCHL");
        string nextKschl = KSCHL.InnerText;

        // ... and so on...

        if (pieces > 0 && totalPrice > 0)
        {
            listResult.Add(new Result(nextKschl, nextKSCHLData, nextEinzelpreis, pieces, totalPrice));
        }
    }
    return listResult;
}

second method: (don't know exactly what to do)

public decimal GetTotalAmount(string amount, string totalAmount)
{
    string total = GetAllKschl(amount, totalAmount); // ??

    return total;
}            

So here I want to have just the TotalAmount (every totalPrice from GetAllKschl) und not the whole list from GetAllKschl. How do I do this?

here my class result:

public class Result
{
    public string KSCHL { get; set; }
    public string Info { get; set; }
    public int individualPrice { get; set; }
    public int Pieces { get; set; }
    public int TotalCosts { get; set; }

    public Result(string kschl, string info, int individualPrice, int pieces, int totalCosts)
    {
        KSCHL = kschl;
        Info = info;
        IndividualPrice = individualPrice;
        Pieces = pieces;
        TotalCosts = totalCosts;
    }
}

Upvotes: 2

Views: 1639

Answers (3)

befree2j
befree2j

Reputation: 371

//In this method you are returning a List
public List<Result> GetAllKschl(string fileNameResult, string fileNameData)
{
    List<Result> listResult = new List<Result>();
    docResult.Load(fileNameResult);
    docData.Load(fileNameData);

    var resultList = docResult.SelectNodes("//root/CalculationLogCompact/CalculationLogRowCompact");

    foreach (XmlNode nextText in resultList)
    {
        XmlNode KSCHL = nextText.SelectSingleNode("KSCHL");
        string nextKschl = KSCHL.InnerText;

        // ... and so on...

        if (pieces > 0 && totalPrice > 0)
        {
            listResult.Add(new Result(nextKschl, nextKSCHLData, nextEinzelpreis, pieces, totalPrice));
        }
    }

    return listResult;
}


//On the second method you returning a decimal and expecting a string    
public decimal GetTotalAmount(string amount, string totalAmount)
{
    string total = GetAllKschl(amount, totalAmount); // ??

    return total;
}   

It would be best to change the second method as:

decimal total = GetAllKschl(amount, totalAmount).Sum(result => result.Gesamtpreis);

Add linq in the return.

Upvotes: 0

Tatranskymedved
Tatranskymedved

Reputation: 4371

The best would be probably using LINQ:

public decimal GetTotalAmount(string amount, string totalAmount)
{
    var total = GetAllKschl(amount, totalAmount).Sum(result => result.Gesamtpreis);

    return total;
} 

I'm assuming that Your result are in the property called Gesamtpreis and is of any numeric type.


EDIT:

Based on the comments I decided to put there a bit more description about LINQ extension methods and lambda method. LINQ methods allows You to use a query language similar to SQL. It works with Collection of elements (e.g. List of Result - List<Result>). On this collection You will call these methods and they will provide You some kind of result, sometimes just number (Aggregate functions like Min,Max,Sum,..) or they will do some other actions returning object or another collection (First,Last, ToList, ToDictionary).

In our care we will have a List with objects:

public class Product
{
    public string Name { get; set; }
    public int Price { get; set; }
}

List<Product> productList = new List<Product>();
productList.Add(new Product() { Name = "Car", Price = 140000 });
productList.Add(new Product() { Name = "SSD Disc", Price = 2000 });
productList.Add(new Product() { Name = "Bananan", Price = 7 });

Having those, for normal SUM You would go with:

int result = 0;
foreach(var nProduct in productList)
    result += nProduct.Price;
Console.WriteLine(result);

This is kind of short code, but it can be pretty much simplified without using variable (for intermediate results) and foreach cycle. (Actually the foreach cycle will be used but we won't need to handle/write it.) LINQ example:

var result = productList.Sum(nProduct => nProduct.Price);

Now this code is much shorter, but we have to split it into several parts to understand what actually happened:

// Saving result to variable (as anytime before)
// Note that I have changed "int" to "var", which simplifies the code,
// as You don't have to take care of "what type will the result be"
// usage is really common with LINQ also
var result = 

// calling method Sum() on the productList
productList.Sum()

// Sum will take each object in the collection and put it as a parameter called "nProduct"
// now the "=>" is something called Lambda syntax,
// that allows take paremeters from the left side and use them in code on the right side.
// left side is instance of "Product" class named as "nProduct"
Sum(nProduct => ... )

// ... is replaced with "nProduct.Price",
// which is selector that tells "make the sum of property "Price"
Sum(nProduct => nProduct.Price)

// In similar manner works other aggregate functions
var max = productList.Max(prod => prod.Price);
var min = productList.Min(prod => prod.Price);
var avg = productList.Average(prod => prod.Price);

Upvotes: 2

Martin Zikmund
Martin Zikmund

Reputation: 39082

You can use LINQ extension method Sum to do so:

decimal total = GetAllKschl( amount, totalAmount ).Sum( result => result.Gesamtpreis );

I assume that the TotalPrice is the name of the property for price in the Result class.

The Sum extension method iterates over all items in the returned collection and sums up the prices.

You could rewrite this without LINQ like this:

var list = GetAllKschl( amount, totalAmount );
decimal total = 0;
foreach ( var item in list )
{
   total += item.Gesamtpreis;
}

As a suggestion, I would recommend making clearer variable naming conventions and do not mix variable names from different languages (English and German).

Also it is quite unusual you used decimal for the total price while Result class uses int. Maybe result should have decimals as well? It seems fitting for a price property.

Upvotes: 3

Related Questions