Selection类具有4个属性:
public class Selection
{
string IdSelectionType {get; set;}
string Name {get; set;}
decimal? OddValue {get; set;}
bool Visible {get; set;}
}
示例数据
var originalList = new List<Selection>()
{
new Selection() {IdSelectionType = "1", Name = "Under (75.50)", Visible = true},
new Selection() {IdSelectionType = "2", Name = "Under (75.50)", Visible = true},
new Selection() {IdSelectionType = "1", Name = "Under (75.50)", OddValue = 1.840m, Visible = true},
new Selection() {IdSelectionType = "2", Name = "Under (75.50)", OddValue = 1.860m, Visible = true},
};
我想选择一个列表,如果存在另一个相同但OddValue = null的元素,则丢弃OddValue = null的元素。
是否有任何Linq / MoreLinq运算符可以执行类似的操作?
Selections.GroupBy(s =>
new {s.IdSelectionType, s.Name, s.OddValue, s.Visible})
.Select(g => g.First()).ToList();
答案 0 :(得分:1)
您可以使用联盟。选择所有不具有OddValue == null的元素,然后将剩余的(带有null的元素)与第一个列表合并。
https://linqsamples.com/linq-to-objects/set/Union
var originalList = new[]
{
new Selection() {IdSelectionType = "1", Name = "Under (75.50)", Visible = true},
new Selection() {IdSelectionType = "2", Name = "Under (75.50)", Visible = true},
//new Selection() {IdSelectionType = "1", Name = "Under (75.50)", OddValue = 1.840m, Visible = true},
new Selection() {IdSelectionType = "2", Name = "Under (75.50)", OddValue = 1.860m, Visible = true},
};
var noneNulls = originalList.Where(ol => ol.OddValue != null);
var endList = originalList
.Where(ol => !noneNulls.Select(nn => nn.IdSelectionType).Contains(ol.IdSelectionType))
.Union(noneNulls);
答案 1 :(得分:1)
var result = items.OrderBy(x => x.Name)
.ThenByDescending(x => x.OddValue)
.GroupBy(s => new {s.IdSelectionType, s.Name, s.Visible})
.Select(x => x.FirstOrDefault())
.ToList();
首先按Name
和OddValue
对项目进行排序,然后按Name
进行分组。在带有OddValue != null
的条目之前,您将拥有带有OddValue == null
的条目。然后获取每个分组的第一项。
这将返回带有OddValue == null
的条目,也不会返回带有相同Name
的其他条目。