-2

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?

lam90
  • 1
  • 2
  • 5
    So you want to create a new list which has only `(double x, double y)`? That sounds rather straightforward to do, what have you tried and where is the problem? – UnholySheep Sep 02 '22 at 12:34
  • Check [this](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples) – Cid Sep 02 '22 at 12:35
  • Related https://stackoverflow.com/questions/1909268/convert-a-list-of-objects-from-one-type-to-another-using-lambda-expression – Christoph Lütjen Sep 02 '22 at 12:38

3 Answers3

2

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.

JonasH
  • 28,608
  • 2
  • 10
  • 23
1

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})");
        }
Mehdi Kacim
  • 131
  • 5
1

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

Jiulia
  • 305
  • 2
  • 10