Search code examples
c#tuples

How to map a List<(string x, string y) from a list of class where i have class.x and class.y in C#?


I have this structure and I want to select / convert MyClass to a simplier list all in one line such as the last line. How can I do it, I want to keep x and y because are significative in the code, so I can use string.x and string.y as I would have done with myClasse.x or myClass.y.

public List<(string x, string y)> strings{ get; set; }

public List<MyClass> myClasses{ get; set; }

public class MyClass {
    public string x,
    public string y,
    ...
}

I cant use the class to make the list of tuples, so i would like something like this.

strings = myClasses.Select(mc => new { x = mc.x, y = mc.y});

I've tried a simple

strings = myClasses.Select(mc => (mc.x, mc.y)).ToList();

but got

CS8143 - An expression tree may not contain a tuple literal.


Solution

  • If I've understood you right, you want to turn MyClass instance into a tuple; it seems you use EF or alike, that's why simple mc => (mc.x, mc.y) doesn't work. Let's use ValueTuple instead:

    mc => new ValueTuple<string, string>(mc.x, mc.y)
    

    and then, the Linq query will be

    strings = myClasses
      .Select(mc => new ValueTuple<string, string>(mc.x, mc.y)) // from MyClass to tuple
      .ToList(); // List of tuples