【问题标题】:How to get one result from a list in another method?如何以另一种方法从列表中获取一个结果?
【发布时间】:2018-07-23 14:02:30
【问题描述】:

大家好,我是 C# 新手。

我尝试从名为“GetAllKschl”的方法返回结果“totalAmount”。在这种方法中,我返回了一个包含“KSCHL、KSCHLData、价格、件数和总价格”的列表。

所以在我的新方法中,我需要所有“totalPrice”的总金额。

第一种方法:

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;
}

第二种方法:(不知道具体怎么做)

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

    return total;
}            

所以在这里我只想拥有 TotalAmount(来自 GetAllKschl 的每个 totalPrice)而不是来自 GetAllKschl 的整个列表。我该怎么做?

这是我的课堂结果:

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;
    }
}

【问题讨论】:

  • 你能告诉我的课程Result吗?
  • string total = GetAllKschl(amount, totalAmount).Count,即如果结果实际上是一个列表而不是某种模态。
  • GetAllKschl 的参数是字符串,但它们似乎指向文件名。
  • @Tatranskymedved 我用它编辑了我的问题。
  • 无关:我建议使用英文变量名。尤其是在这种情况下,您在国际论坛上寻求支持会派上用场。第二:我建议重新考虑选择 int 作为数量,尽管它比 double 好。见stackoverflow.com/a/693376/982149stackoverflow.com/a/3730040/982149

标签: c#


【解决方案1】:

您可以使用 LINQ 扩展方法Sum 这样做:

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

我假设TotalPriceResult 类中价格属性的名称。

Sum 扩展方法遍历返回集合中的所有项目并总结价格。

你可以像这样在没有 LINQ 的情况下重写它:

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

作为一项建议,我建议制定更清晰的变量命名约定,不要混合使用不同语言(英语和德语)的变量名。

另外,您使用decimal 作为总价,而Result 类使用int 也是很不寻常的。也许结果也应该有decimals?它似乎适合价格属性。

【讨论】:

  • string amount, string totalAmount写方法对吗?还是我这里也需要小数点?
  • 只要amounttotalAmount变量包含文件名就可以了。但是它们应该被命名为不同的名称,如amountFileNametotalAmountFileName,以明确它们代表什么
  • 是的,它应该与第一种方法中的文件相同(fileNameResult,fileNameData)。那么我是否也必须在此方法中加载这些文件?
  • 你的意思是如何加载这个方法?你调用方法来得到结果,对不对?文件将被加载到内部,并将数据作为Result 实例列表返回。问题是你如何调用GetTotalAmount 方法?
  • 是的,没错。在第一种方法中,文件将被加载并返回一个包含我需要的所有东西的列表。然后在第二个我只需要 TotalPrice。那么我如何调用该方法是什么意思?不对吗?
【解决方案2】:

最好的可能是使用LINQ

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

    return total;
} 

我假设您的结果在名为 Gesamtpreis 的属性中,并且是任何数字类型。


编辑:

基于 cmets,我决定对 LINQ 扩展方法和 lambda 方法进行更多描述。 LINQ 方法允许您使用类似于 SQL 的查询语言。它适用于 Collection 的元素(例如 ListResult - List&lt;Result&gt;)。在这个集合上,您将调用这些方法,它们会为您提供某种结果,有时只是数字(聚合函数,如 MinMaxSum、..),或者它们会执行一些其他操作返回对象或另一个集合(FirstLastToListToDictionary)。

在我们的照顾下,我们将拥有一个包含对象的列表:

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 });

拥有这些,对于正常的 SUM 你会选择:

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

这是一种简短的代码,但它可以在不使用变量(用于中间结果)和foreach 循环的情况下大大简化。 (实际上会使用foreach循环,但我们不需要处理/编写它。)LINQ示例:

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

现在这段代码要短得多,但我们必须把它分成几个部分来了解实际发生了什么:

// 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);

【讨论】:

  • 是的,Geamtpreis 是我班级结果中的TotalPrice。我需要写Result result = new Result();?然后是new Result(...)开头的所有参数?
  • LINQ 语法Sum(result =&gt; /* some code here */ ):有一个特殊的方法叫做Sum,它接受一个参数(在我们的例子中叫做result),并且会在=&gt;的右边执行查询.使用不同的名称:通过写入myList.Sum(a =&gt; a.Price),我们将对myList 中的所有Price 进行汇总。请点击我的回答中的“LINQ”以查看更多详细信息。
  • 啊,我明白了。对不起,我不习惯 LINQ,它不再令人困惑,哈哈 :) 但是谢谢!
  • @Ronja 它是 LINQ 扩展方法结合 Lambda 语法(两个独立的东西),我在一年前开始使用它,我强烈建议学习它。它确实简化了代码并用几行代码解决了很多问题。
  • @Fildor -> 我同意,我将对 LINQ 进行更多描述。然而,另一个答案提供了“如何”不带 LINQ 的信息。
【解决方案3】:
//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;
}   

最好把第二种方法改成:

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

在返回中添加 linq。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多