元素分组和排序

时间:2018-07-31 07:18:12

标签: c# linq

public class RebarUnique
{
    public Rebar MRebar { get; set; }
    public Point2d Point2d { get; set; }
}

public class Rebar
{
    public string Number { get; set; }
    public int Type { get; set; }
    public int Fi { get; set; }
}

我有清单:

List<RebarUnique> rebarUnique;

[{{Number: 1, Type: 1, Fi: 12}, (0,0)},

{{Number: 1, Type: 1, Fi: 12}, (0,10)},

{{Number: 2, Type: 1, Fi: 12}, (15,18)},

{{Number: 3, Type: 1, Fi: 12}, (25,34)},

{{Number: 1, Type: 1, Fi: 12}, (25,34)},

{{Number: 3, Type: 1, Fi: 12}, (13,38)}]

我想要一个列表:

  • Number分组

  • Point2dY coordinate)排序

  • 返回最低Number

  • 的列表(Y coordinate

2 个答案:

答案 0 :(得分:2)

类似的事情应该起作用:

var rebarUniqueL = rebarUnique
    .GroupBy(x => x.MRebar.Number)
    .Select(x => x.OrderBy(y => y.Point2d.Y).First())
    .ToList();

答案 1 :(得分:0)

rebarUnique.OrderBy(x => x.Point2d.Y) // Order the items by Y
    .GroupBy(x => x.MRebar.Number) //Then group them by number, within each group the items are still sorted by Y
    .Select(g => new {Number = g.Key, Item = g.First()) // get lowest Y for each number
    .ToList();

输出:

Number   Item    
1        {{Number: 1, Type: 1, Fi: 12}, (0,0)}
2        {{Number: 2, Type: 1, Fi: 12}, (15,18)}
3        {{Number: 3, Type: 1, Fi: 12}, (25,34)},