C# LINQ 查询,如果为空,则使用上一个结果

本文关键字:上一个 结果 LINQ 查询 如果 | 更新日期: 2023-09-27 18:37:05

我有一个从访问数据库填充的数据表。结果看起来像

Month | Sum
--------------
1 | 1464
2 | 1716
3 | 2125
4 | 2271
5 | 2451
6 | 2583
7 | 2671
9 | 2823
10 | 2975

你是对的 - 八月什么都没有!我想要的是,对于 8 月,使用与 7 月相同的值。目前,我正在使用此 LINQ 查询将数据添加到折线图:

for (int i = 1; i <= System.DateTime.Now.Month; i++)
            {
                var numbers = (from p in dTable.AsEnumerable()
                              where p.Field<int>("M") >= i
                              select p).First();                   
                series2.Points.Add(new DataPoint { AxisLabel = i.ToString(), YValues = new double[] { Convert.ToDouble(numbers["Sum"]) } });  
            }

将显示图表,但对于 8 月,将使用 9 月值。我认为我做错了是非常基本的事情,但我根本无法弄清楚。提前感谢!

C# LINQ 查询,如果为空,则使用上一个结果

您请求的所有月份都大于当前月份。

where p.Field<int>("M") >= i

因此,对于 8 月 (8),您检索的是 9 月及更大 (9、10、11、12),而不是 7 月 (7)。

您必须反转约束,并按月份降序排序:

var numbers = (from p in dTable.AsEnumerable()
                          where p.Field<int>("M") <= i
                          select p)
                         .OrderByDesc(p => p.Month) 
                         .First();   

你必须反转你的逻辑:

var numbers = (from p in dTable.AsEnumerable()
               where p.Field<int>("M") <= i
               select p).Last();

不用说,当没有上个月时,这是行不通的。

更新:

以上假设您正在从中读取的表是有序的。如果不是这种情况,你必须自己订购(如Cyril Gandon所提到的):

var numbers = (from p in dTable.AsEnumerable()
               where p.Field<int>("M") <= i
               orderby p.Field<int>("M") descending
               select p).First();