c# – GroupBy后的条件选择
发布时间:2020-12-15 23:30:35 所属栏目:百科 来源:网络整理
导读:如何编写条件在GroupBy之后根据if语句选择项目? 我有一个Option类型的对象列表: class Option { public Boolean Important { get; set; } public int Priority { get; set; } public String Value { get; set; } public String Name { get; set; }} 我初始
如何编写条件在GroupBy之后根据if语句选择项目?
我有一个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,Value = "Blue" },new Option { Priority = 100,Name = "Font",Value = "16" },Value = "32" }; 所以我有类似的东西: ///MY Options/// /// NAME --- VALUE --- PRIORITY --- IMPORTANT /// Color -- Red ----- 100----------True /// Color -- Blue ---- 150----------False /// Font-----16--------100----------False /// Font-----32--------150----------False /// 我需要按名称对它们进行分组,并根据两个语句获取这些值: >选择最重要的一个,重要的是真的. 所以目标应该是: ///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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |