将foreach转换为linq以解决运行平衡问题

时间:2015-07-10 16:43:26

标签: c# linq

我是linq的新人,并在网上阅读了一些关于他们的内容。

现在,下面的查询工作正常,可以从当前日期计算项目12个月的运行余额。是否可以将其转换为linq?

这将有助于我更好地理解linq。

    var firstDayMonth = new DateTimeOffset(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1));
    var months = Enumerable.Range(0, 12)
                           .Select(m => firstDayMonth.AddMonths(m));

    List<SomeDate> SomeDates = new List<SomeDate>()
    {
        new SomeDate { Id = 7, Month = firstDayMonth.AddMonths(0), Balance = 1m },
        new SomeDate { Id = 7, Month = firstDayMonth.AddMonths(0), Balance = 3m },
        new SomeDate { Id = 8, Month = firstDayMonth.AddMonths(1), Balance = 6m },
        new SomeDate { Id = 8, Month = firstDayMonth.AddMonths(1), Balance = 5m },
        new SomeDate { Id = 8, Month = firstDayMonth.AddMonths(1), Balance = 3m },
        new SomeDate { Id = 9, Month = firstDayMonth.AddMonths(2), Balance = 5m },
        new SomeDate { Id = 10, Month = firstDayMonth.AddMonths(3), Balance = 3m },
        new SomeDate { Id = 12, Month = firstDayMonth.AddMonths(5), Balance = 15m },
        new SomeDate { Id = 13, Month = firstDayMonth.AddMonths(6), Balance = 16m },
        new SomeDate { Id = 13, Month = firstDayMonth.AddMonths(6), Balance = 12m },
    };

    var projected12MonthsBalance = new List<SomeDate>();

    foreach(var month in months)
    {
        projected12MonthsBalance.Add(new SomeDate { Month = month, Balance = SomeDates.TakeWhile(s => s.Month <= month).Sum(s => s.Balance) });
    }

    Console.WriteLine(projected12MonthsBalance);

public class SomeDate 
{
    public int Id { get; set; }
    public DateTimeOffset Month { get; set; }
    public decimal Balance { get; set; }
}

1 个答案:

答案 0 :(得分:2)

试试这个:

Function HasValidation(cell As Range) As Boolean
    Dim t: t = Null

    On Error Resume Next
    t = cell.Validation.Type
    On Error GoTo 0

    HasValidation = Not IsNull(t)
End Function