Home > Net >  Taking the x, y from a list of x, y, z C#
Taking the x, y from a list of x, y, z C#

Time:09-03

I'm writing some code in C#, I have a list = new List<(double x, double y, double z)>, however I need to get the x and y into their own list to perform some maths on these points. Could I please have some ideas on how to achieve this?

CodePudding user response:

Just use LINQ

myList.Select( p => (p.X, p.Y)).ToList();

I would however highly recommend creating actual types for your points/vectors rather than using tuples, i.e. Vector3D/Vector2D. Since you would typically expect things like operators to add vectors/points and much more functionality that is missing on tuples.

CodePudding user response:

try following code

      //       x      y       z
        List<(double, double, double)> values = new List<(double, double, double)>();
        values.Add((1, 2, 3));
        values.Add((4, 5, 6));
        values.Add((7, 8, 9));
        var coords = values.Select(d => new { x = d.Item1, y = d.Item2 });

        foreach(var coord in coords)
        {
            Console.WriteLine($"(x;y) =>({coord.x};{coord.y})");
        }

CodePudding user response:

By using Language Integrated Queries (linq) in System.Collections.Generic

var vec3list = new List<(double x, double y, double z)>() { /*bla bla bla*/ };
IEnumerable<(double x, double y)> vec2list = vec3list.Select(v3 => (v3.x, v3.y));

IEnumerables enumerate over the original list in a deferred read-only way.

Check M$ docs on the topic

As a side note, i strongly suggest you use a struct to hold your data. Tuples are more for the "i need to return multiple unrelated things from my method" scenario

  • Related