我应该如何在 GroupBy
之后根据 if
语句编写条件 Where
到 Select
项目?
我有一个类型为 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
///
我需要按名称对它们进行分组,并根据两个语句获取这些值:
- 取
Important
为 true 的最优先级。 - 如果没有
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/