c# - 用 List<T> 解构

标签 c# .net-core tuples .net-core-2.1 c#-7.3

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

我在使用以下代码示例时遇到以下编译错误:

Cannot implicitly convert type 'System.Collections.Generic.List< Deconstruct.Test>' to '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....
        }
    }
}

最佳答案

您需要显式转换 testList ( List<Test> ) 到 tupleList ( List<(int, int)> )

tupleList = testList.Select(t => (t.A, t.B)).ToList();

说明:

您使用的代码就好像 Deconstruct让您转换一个实现 Deconstruct 的类到一个元组( ValueTuple ),但这不是 Deconstruct剂量。

来自文档 Deconstructing tuples and other types :

Starting with C# 7.0, you can retrieve multiple elements from a tuple or retrieve multiple field, property, and computed values from an object in a single deconstruct operation. When you deconstruct a tuple, you assign its elements to individual variables. When you deconstruct an object, you assign selected values to individual variables.

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

正在尝试转换 List<Test>List<(int, int)>像这样:

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

无法工作,因为您无法转换 List<Test>List<(int, int)> .它将产生一个编译器错误:

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List<(int, int)>'

尝试转换每个 Test元素到 (int, int)像这样:

tupleList = testList.Cast<(int, int)>().ToList();

无法工作,因为您无法转换 Test(int, int) .它将产生一个运行时错误:

System.InvalidCastException: 'Specified cast is not valid.'

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

(int, int) tuple = test;

无法工作,因为您无法转换 Test(int, int) .它将产生一个编译器错误:

Cannot implicitly convert type 'Deconstruct.Test' to '(int, int)'

关于c# - 用 List<T> 解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723303/

相关文章:

c# - Nlog 从 Appsettings 获取 Azure Blob 存储连接字符串

Python 元组而不是列表

haskell - "zipping"相同长度的元组是否有 Haskell 镜头功能?

c# - .net 4.0 中并行化网络爬虫的最佳实践

c# - 如何在 Nsubstitute 中使用内部服务?

带前导空格的 C# 格式货币?

angular - 仅在 Angular 通用中将组件标记为客户端

compiler-errors - Swift 错误类型 'T' 不符合协议(protocol) 'IntegerLiteralConvertible'

c# - 由于特殊字符,在 VB.Net 中解析 XML 失败

c# - 使用 IdentityServer4.AccessTokenValidation 包向 IdentityServer3 授权 .NET 5 Web API 引用 token 时出现问题