-1

我在列表中有一些 3D 数据:

myDataList[0] - { X: 164 , Y: 79 , Z: 120 }
myDataList[1] - { X: 146 , Y: 63 , Z: 120 }
myDataList[2] - { X: 192 , Y: 59 , Z: 120 }
myDataList[3] - { X: 196 , Y: 59 , Z: 120 }
myDataList[4] - { X: 110 , Y: 55 , Z: 120 }
myDataList[5] - { X: 148 , Y: 69 , Z: 122 }
myDataList[6] - { X: 194 , Y: 59 , Z: 122 }
myDataList[7] - { X:  18 , Y: 47 , Z: 122 }

我想基于相同的 Z 坐标获得 X 和 Y 坐标

我正在尝试通过循环以 LINQ 方式执行此操作。

for (int i = 0; i < myDataList.Count; i++)
{
    myXList = myDataList.Where(x => myDataList[i].Z == myDataList[i + 1]).Select(x => x.X).ToList();

    myYList = myDataList.Where(y => myDataList[i].Z == myDataList[i + 1]).Select(y => y.Y).ToList();
}

但我现在的问题是如何从列表中区分相同的 Z 并选择 X 和 Y。上面的for循环是错误的,因为它只检查不同的 Zii + 1但不是同时检查所有 i。

有帮手吗?

4

2 回答 2

2

就像是:

var grouped = from p in myDataList
              group p by p.Z into q
              select q;

// Or, equivalent considering you don't have to reuse q
var grouped2 = from p in myDataList
               group p by p.Z;

// Or, equivalent using functional LINQ
var grouped3 = myDataList.GroupBy(p => p.Z);

foreach (var group in grouped)
{
    int z = group.Key;

    foreach (var element in group)
    {
        // Where element is the "original" object
        int x = element.X;
        int y = element.Y;
        int z2 = element.Z; // same as z
    }
}

从技术上讲,甚至还有.ToLookup一种方法,类似于GroupBy

var grouped4 = myDataList.ToLookup(p => p.Z);

结果组的使用方式与.GroupBy. 差异是微妙的...... https://stackoverflow.com/a/1337567/613130

于 2013-08-09T09:35:11.093 回答
0
var coordinates = new List<Coordinate>()
{
    new Coordinate { X = 164 , Y = 79 , Z = 120 },
    new Coordinate { X = 146 , Y = 63 , Z = 120 },
    new Coordinate { X = 192 , Y = 59 , Z = 120 },
    new Coordinate { X = 196 , Y = 59 , Z = 120 },
    new Coordinate { X = 110 , Y = 55 , Z = 120 },
    new Coordinate { X = 148 , Y = 69 , Z = 122 },
    new Coordinate { X = 194 , Y = 59 , Z = 122 },
    new Coordinate { X =  18 , Y = 47 , Z = 122 }
};

var grouped = coordinates
    .Select(c => c.Z)
    .Distinct()
    .ToDictionary(
        z => z, 
        z => coordinates.Where(c => c.Z == z));
于 2013-08-09T09:54:06.453 回答