如何映射列表<(string x, string y) from a list of class where i have class.x and class.y in C#?

问题描述 投票:0回答:1

我有这个结构,我想将我的类“选择/转换”为一个更简单的列表,全部在一行中,例如最后一行我该怎么做,我想保留 x 和 y 因为它们在代码中很重要,所以我可以使用 string.x 和 string.y,就像使用 myClasse.x 或 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,
    ...
}

我无法使用该类来制作元组列表,所以我想要这样的东西。

strings = myClasses.Select(mc => new { x = mc.x, y = mc.y});
c#
1个回答
0
投票

如果我没理解错的话,你想将

MyClass
实例转换为 tuple;看来你使用 EF 或类似的,这就是为什么简单的
mc => (mc.x, mc.y)
不起作用。让我们用
ValueTuple
来代替:

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

然后,Linq 查询将是

strings = myClasses
  .Select(mc => new ValueTuple<string, string>(mc.x, mc.y)) // from MyClass to tuple
  .ToList(); // List of tuples   
© www.soinside.com 2019 - 2024. All rights reserved.