c# - GroupBy 之后的条件选择

标签 c# linq lambda

我应该如何在 GroupBy 之后根据 if 语句编写条件 WhereSelect 项目?

我有一个类型为 Option 的对象列表:

class Option {
    public Boolean Important { get; set; }
    public int Priority { get; set; }
    public String Value { get; set; }
    public String Name { get; set; }
}

我初始化我的选项和一个包含所有选项的列表:

List<Option> myOptions = new List<Option> {
    new Option { Priority = 100, Name = "Color", Value = "Red", Important = true },
    new Option { Priority = 150, Name = "Color", Value = "Blue" },
    new Option { Priority = 100, Name = "Font", Value = "16" },
    new Option { Priority = 150, Name = "Font", Value = "32"
};

所以我有这样的东西:

///MY Options///
/// NAME --- VALUE --- PRIORITY --- IMPORTANT
/// Color -- Red ----- 100----------True
/// Color -- Blue ---- 150----------False
/// Font-----16--------100----------False
/// Font-----32--------150----------False
/// 

我需要按名称对它们进行分组,并根据两个语句获取这些值:

  1. Important 为 true 的最优先级。
  2. 如果没有Important 的项目,则选择优先级最高的项目。

所以目标应该是:

    ///Color - Red  //Because has the most priority being Important
    ///Font - 32    //Because has the most priority and there's no Important

我试图避免多次迭代,所以我正在构建一个 Linq 查询...没有成功。

.Select(g => new {
    Name = g.Key,
     Value = g.Where(op => op.Important).OrderByDescending(op => op.Priority).First().Value
}).ToList();

我不知道如何解析Where。有什么想法吗?

最佳答案

听起来您并不是真的想按“重要”过滤,而是按它排序:

Value = g.OrderByDescending(op => op.Important) // true first
         .ThenByDescending(op => op.Priority)
         .First()
         .Value

关于c# - GroupBy 之后的条件选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34898486/

相关文章:

c# - DbMigrator 在切换数据库后未检测到挂起的迁移

C# Dice Times 每个数字被滚动

LINQ 查询中的 C# lambda 表达式

c# - 生成给定字符串列表的子列表

Python:获取 Lambda 函数的总和

c# - 灵活使用对象包装器类

c# - 如何构建印度尼西亚电话号码正则表达式

c# - Linq 无法从 'System.Collections.Generic.IEnumerable<string>' 转换为 'string[]'

haskell - 如何将 Haskell 中的匿名函数的折叠重写为常规函数?

c# - 使用 LINQ 分离列表