c# - 在 LINQ 查询中使用 Max - 列表中的空值

标签 c# linq

我正在尝试获取(SecKey 的)最大值,因为我有一个项目的空值,Linq 结果给我第一个值(在本例中为 40)。 SecKey 值应为 200。如何解决此问题?

我试过了

SecKey = groupedList.Max(d => string.IsNullOrEmpty(d.SecKey) ? "0" : d.SecKey) 

但是没用!

var newData = from list in myList
    group list by new { list.BadgeNum, list.ActiveDate, list.EndDate }
        into groupedList
        select new
        {
            groupedList.Key.BadgeNum,
            groupedList.Key.ActiveDate,
            groupedList.Key.EndDate,
            Amount = groupedList.Sum(a => a.Amount)
            SecKey = groupedList.Max(d => d.SecKey)
        };

这是我在 myList 中的数据

BadgeNum    ActiveDate  EndDate Amount  SecKey
722711      1/1/2014    1/31/2014   10  40
722711      1/1/2014    1/31/2014   10  
722711      1/1/2014    1/31/2014   70  200

当前输出:

BadgeNum    ActiveDate  EndDate Amount  SecKey
722711      1/1/2014    1/31/2014   90  40

预期输出:

BadgeNum    ActiveDate  EndDate Amount  SecKey
722711      1/1/2014    1/31/2014   90  200

最佳答案

这不会发生,因为列表中有 null - Max 会忽略它们。

问题是您为 SecKey 使用的数据类型将 40 排在 200 之前。例如,如果您为 SecKey 使用字符串,则可能会发生这种情况,在这种情况下,'200' 按字典顺序会比 ' 40'

如果您无法控制数据类型,您可以通过按升序将组转换为 int 并获取最后一个元素(或按降序排序和取第一个元素),像这样:

SecKey = groupedList.OrderBy(d => Convert.ToInt32(d.SecKey)).Last().SecKey;

关于c# - 在 LINQ 查询中使用 Max - 列表中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27724297/

相关文章:

c# - ASP.NET MVC ViewData.Model 需要转换

c# - 从另一个页面的代码隐藏中获取 ASP.Net 页面的 URL

c# - 连接对象数组中的唯一字符串

c# - 如何使用嵌套的 ObservableCollection 将数据 LINQ 到 ObservableCollection 中?

c# - 从列表中删除相似的矩形

c# - 使 .NET TextBox 工作 FIFO 风格

c# - 如何在项目之间重用几乎相同的代码?

c# - 子查询中的 LINQ-to-SQL 和扩展方法

c# - 如何在通过 Html.ValidationSummary() 呈现的错误中显示链接等 html 元素

c# - 使 LINQ 查询更好