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