Linq GroupBy并接受不为空的条目

时间:2018-09-13 11:02:05

标签: c# linq

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();

enter image description here

预期结果将是: enter image description here

2 个答案:

答案 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);

工作示例:https://dotnetfiddle.net/UJ8FaS

答案 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();

首先按NameOddValue对项目进行排序,然后按Name进行分组。在带有OddValue != null的条目之前,您将拥有带有OddValue == null的条目。然后获取每个分组的第一项。

这将返回带有OddValue == null的条目,也不会返回带有相同Name的其他条目。

最终结果:https://dotnetfiddle.net/jZ5gs2