用List <T>解构

rhu*_*hes 4 c# tuples .net-core c#-7.3 .net-core-2.1

有没有办法让元组列表解构为List<T>

我收到以下代码示例的以下编译错误:

无法将类型'System.Collections.Generic.List <Deconstruct.Test>'隐式转换为'System.Collections.Generic.List <(int,int)>'

using System;
using System.Collections.Generic;

namespace Deconstruct
{
    class Test
    {
        public int A { get; set; } = 0;

        public int B { get; set; } = 0;

        public void Deconstruct(out int a, out int b)
        {
            a = this.A;
            b = this.B;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var test = new Test();

            var (a, b) = test;

            var testList = new List<Test>();

            var tupleList = new List<(int, int)>();

            tupleList = testList; // ERROR HERE....
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Eli*_*ron 7

您需要将testListList<Test>)明确转换为tupleListList<(int, int)>

tupleList = testList.Select(t => (t.A, t.B)).ToList();
Run Code Online (Sandbox Code Playgroud)

说明:

您正在使用该代码,就好像Deconstruct您可以将实现的类转换Deconstruct为元组(ValueTuple)一样,但这不是什么Deconstruct

从文档解构元组和其他类型

从C#7.0开始,您可以在一个解构操作中从一个元组检索多个元素,或从一个对象检索多个字段,属性和计算值。解构元组时,可以将其元素分配给各个变量。解构对象时,将选定的值分配给各个变量

解构将多个元素返回给单个变量,而不是元组(ValueTuple)。

尝试将a转换List<Test>List<(int, int)>如下形式:

var testList = new List<Test>();
var tupleList = new List<(int, int)>();
tupleList = testList;
Run Code Online (Sandbox Code Playgroud)

不行,因为你不能转换List<Test>List<(int, int)>。它将生成编译器错误:

无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.List <(int,int)>'

尝试将每个Test元素强制转换为(int, int)如下形式:

tupleList = testList.Cast<(int, int)>().ToList();
Run Code Online (Sandbox Code Playgroud)

无法运作,因为您无法将强制Test转换为(int, int)。它将生成运行时错误:

System.InvalidCastException:'指定的强制转换无效。

尝试将单个Test元素转换成(int, int)这样:

(int, int) tuple = test;
Run Code Online (Sandbox Code Playgroud)

不行,因为你不能转换Test(int, int)。它将生成一个编译器错误:

无法将类型'Deconstruct.Test'隐式转换为'(int,int)'