计算多个不同的值-Linq

时间:2019-07-08 17:00:22

标签: c# performance linq

我有一个的列表(每个点具有id,x,y,z属性)。

我想获取属性x,y,z

总不同值

我在做:

var points = new List<MyPoint>
{
    new MyPoint {Id = 0, X = 97.5, Y = 92.5, Z = -16.6666660308838},
    new MyPoint {Id = 1, X = 292.5, Y = 92.5, Z = -16.6666660308838},
    new MyPoint {Id = 2, X = 97.5, Y = 277.5, Z = -16.6666660308838},
    new MyPoint {Id = 3, X = 292.5, Y = 277.5, Z = -16.6666660308838},
    new MyPoint {Id = 4, X = 97.5, Y = 462.5, Z = -16.6666660308838},
    new MyPoint {Id = 5, X = 292.5, Y = 462.5, Z = -16.6666660308838},
    new MyPoint {Id = 6, X = 97.5, Y = 92.5, Z = -49.9999980926514},
    new MyPoint {Id = 7, X = 292.5, Y = 92.5, Z = -49.9999980926514},
    new MyPoint {Id = 8, X = 97.5, Y = 277.5, Z = -49.9999980926514},
    new MyPoint {Id = 9, X = 292.5, Y = 277.5, Z = -49.9999980926514},
    new MyPoint {Id = 10, X = 97.5, Y = 462.5, Z = -49.9999980926514},
    new MyPoint {Id = 11, X = 292.5, Y = 462.5, Z = -49.9999980926514},
    new MyPoint {Id = 12, X = 97.5, Y = 92.5, Z = -83.3333320617676},
    new MyPoint {Id = 13, X = 292.5, Y = 92.5, Z = -83.3333320617676},
    new MyPoint {Id = 14, X = 97.5, Y = 277.5, Z = -83.3333320617676},
    new MyPoint {Id = 15, X = 292.5, Y = 277.5, Z = -83.3333320617676},
    new MyPoint {Id = 16, X = 97.5, Y = 462.5, Z = -83.3333320617676},
    new MyPoint {Id = 17, X = 292.5, Y = 462.5, Z = -83.3333320617676}
};
var result =
    points
    .GroupBy(l => l.Id)
    .Select(g => new
    {
        sizeX = g.Select(l => l.X).Distinct().Count(),
        sizeY = g.Select(l => l.Y).Distinct().Count(),
        sizeZ = g.Select(l => l.Z).Distinct().Count()
    });

我得到这个:

enter image description here

我该如何解决这个问题

X ->2
Y ->3
Z ->3

2 个答案:

答案 0 :(得分:5)

正在遵循您的需求吗?

var result = new
{
    sizeX = points.Select(l => l.X).Distinct().Count(),
    sizeY = points.Select(l => l.Y).Distinct().Count(),
    sizeZ = points.Select(l => l.Z).Distinct().Count()
};

答案 1 :(得分:4)

您可以执行以下操作:

    HashSet<double> xes = new HashSet<double>();
    HashSet<double> yes = new HashSet<double>();
    HashSet<double> zes = new HashSet<double>();

    foreach (MyPoint pt in list)
    {
      xes.Add(pt.X);
      yes.Add(pt.Y);
      zes.Add(pt.Z);
    }

,然后在哈希集上调用Count

int countX = xes.Count; etc...

    HashSet<double> xes = new HashSet<double>();
    HashSet<double> yes = new HashSet<double>();
    HashSet<double> zes = new HashSet<double>();

    list.Aggregate((xes, yes, zes), (acc, pt) =>
    {
      acc.xes.Add(pt.X);
      acc.yes.Add(pt.Y);
      acc.zes.Add(pt.Z);
      return acc;
    });

,然后在哈希集上调用Count

int countX = xes.Count; etc...