Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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" my class 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading