温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Is there a way to Translate an array into a dictionary

c# - 有没有办法将数组翻译成字典

发布于 2020-03-27 11:55:33

我遇到的问题是我不确定如何将double数组转换为Dictionary我有一些Where很沉重的LINQ 语句,因此我想使用我的键Dictionary来查找特定值。我有两个课程,分别是getter和setter,然后是计算器。

我在尝试进行查找或时花了些力气Dictionary,但没有任何运气。

public class Product
{
    public int EarliestOriginYear { get; set; }
    public int NoOfDevelopmentYears { get; set; }
    public string ProductName { get; set; }
    public IEnumerable<ProductIncrementalValue> ProductIncrementalValues { get; set; }
}

public class ProductIncrementalValue
{
    public string ProductName { get; set; }
    public int OriginYear { get; set; }
    public int DevelopmentYear { get; set; }
    public double IncrementalValue { get; set; }
}

public IList<double> Calculate(Product product)
{
     IList<double> cumulativeDataTriangle = new List<double>();
     if (!product.ProductIncrementalValues.Any())
        return cumulativeDataTriangle;

     for (int i = 0; i < product.NoOfDevelopmentYears; i++)
     {
        // This is what I want to change (where statements)
        var incrementalValues = product.ProductIncrementalValues
            .Where(v => v.OriginYear == product.EarliestOriginYear + i)
            .ToList(); 

        double previous = 0;

        for (int j = 0; j < product.NoOfDevelopmentYears - i; j++)
        {
            // This is what I want to change
            double incrementalValue = incrementalValues.Where(val =>
                val.DevelopmentYear == val.OriginYear + j)
                .Select(x => x.IncrementalValue)
                .FirstOrDefault();

            var tmp = incrementalValue + previous;
            cumulativeDataTriangle.Add(tmp);
            previous = tmp;
        }
     }

     return cumulativeDataTriangle;
}

查看更多

查看更多

提问者
user11251276
被浏览
44
cem 2019-07-04 00:32

你可以组产品通过OriginYearDevelopmentYear环之前。这样的事情可能会有所帮助:

public IList<double> Calculate(Product product)
{
    IList<double> cumulativeDataTriangle = new List<double>();
    if (!product.ProductIncrementalValues.Any())
        return cumulativeDataTriangle;

    var lookup = product.ProductIncrementalValues.ToLookup(v => (v.OriginYear, v.DevelopmentYear), v => v.IncrementalValue); 
    for (int i = 0; i < product.NoOfDevelopmentYears; i++)
    {
        var originYear = product.EarliestOriginYear + i;
        double previous = 0;
        for (int j = 0; j < product.NoOfDevelopmentYears - i; j++)
        {
            var developmentYear = originYear + j;
            var incrementalValues = lookup[(originYear, developmentYear)];
            double incrementalValue = incrementalValues.FirstOrDefault();

            var tmp = incrementalValue + previous;
            cumulativeDataTriangle.Add(tmp);
            previous = tmp;
        }
    }

    return cumulativeDataTriangle;
}

发布
问题

分享
好友

手机
浏览

扫码手机浏览