C#返回对象中的多个值

时间:2017-02-22 15:04:38

标签: c# list return

我有一个应该返回多个值的方法(AlphaCalcResult)。每个forloop都有一些逻辑可以为List字段赋值。然后,我想返回结果对象,其中包含从下面描述的两个循环生成的两个值。 C#开发的新手,并且语法有问题。

我如何在下面的代码中使用return语句?

public AlphaCalcResult CalculateAlpha(AlphaCalcParam param)
{
    AlphaCalcResult result = new AlphaCalcResult
    {
        portfolios = new List<Portfolio>()
    };

    // Lists Portfolios & Settings
    var portfolioListItem = param.portfolios.portfolioHoldings;
    var scoreListItem = param.settings.grossAlphas;

    // 1. CALCULATE FUND ALPHA
    for (var i = 0; i<portfolioListItem.Count; i++)
    {
        portfolioListItem[i].fundRating = i;

        for (var j = 0; j<scoreListItem.Count; j++)
        {
            scoreListItem[j].fundRating = j;

            if(i == j)
            {
               portfolioListItem[i].fundAlpha = scoreListItem[j].grossAlpha - portfolioListItem[i].fundExpenseRatio;
            }
        }
    }

    //2. CALCULATE PORTFOLIO ALPHA
    var portfolioAlphaResult = param.portfolios.portfolioAlpha;
    for (var i =0; i<portfolioListItem.Count; i++)
    {
        portfolioAlphaResult = portfolioListItem[i].fundWeight * portfolioListItem[i].fundAlpha;
    };

    // populate result
    return result;
    }

3 个答案:

答案 0 :(得分:1)

我不确定这是否真的是你在这个例子中做的,但你可以使用.NET 4.0 +的元组类型返回多个值。

例如:

public Tuple<string, int> GetValues()
{
     return Tuple.Create("first",2);
}

// usage:
var result = GetValues();
var theString = result.Item1;
var theInt = result.Item2;

答案 1 :(得分:1)

更改此部分:

//2. CALCULATE PORTFOLIO ALPHA
var portfolioAlphaResult = param.portfolios.portfolioAlpha;
for (var i =0; i<portfolioListItem.Count; i++)
{
    portfolioAlphaResult = portfolioListItem[i].fundWeight * portfolioListItem[i].fundAlpha;
    (result.portfolios as List<Portfolio>).Add(new Portfolio() { portfolioAlpha = portfolioAlphaResult });

};

答案 2 :(得分:1)

首先将public IEnumerable<Portfolio> portfolios { get; set; }更改为

public List<Portfolio> portfolios { get; set; } 

因为IEnumerable用于阅读列表而在您的代码中添加

 //2. CALCULATE PORTFOLIO ALPHA
         for (var i =0; i<portfolioListItem.Count; i++)
            {

        List<PortfolioHolding> list = new List<PortfolioHolding>();
        list=portfolioListItem;
        Portfolio port = new Portfolio();
        port.portfolioIdentifier = "current";
        port.portfolioAlpha = portfolioListItem[i].fundWeight * portfolioListItem[i].fundAlpha;
        port.portfolioHoldings = list;
        result.portfolios.Add(port);

        };