-1

I have some 3D data inside a list:

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 }

I want to get the X and Y coordinate based on the same Z coordinate

I am trying to do this in LINQ way with a loop.

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

But my problem now is how to distinct the same Z from the list and select the X and Y. The above for loop is wrong because it is only checking the the distinct Z for i and i + 1 But not all the i at once.

Any helping hand?

jhyap
  • 3,779
  • 6
  • 27
  • 47

2 Answers2

2

Something like:

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
    }
}

Technically there is even the .ToLookup method, that is similar to the GroupBy

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

The resulting groups are used like the ones generated by the .GroupBy . The differences are subtle... https://stackoverflow.com/a/1337567/613130

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280
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));
gislikonrad
  • 3,401
  • 2
  • 22
  • 24