【问题标题】:List does not contain a definition for 'ConvertAll' and no extension method 'ConvertAll' accepting a first argument of type 'List< >'List 不包含“ConvertAll”的定义,并且没有扩展方法“ConvertAll”接受“List< >”类型的第一个参数
【发布时间】:2017-09-28 12:02:12
【问题描述】:

我正在开发一个在 Visual Studio 命令上运行的 C# 项目。看起来是这样的:

using System;
using System.Linq;
using System.Collections.Generic;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            var usuarios = new List<Usuario>() {
                new Usuario() { Id = 5, Grupo = "Diretoria", Nome = "Carlos" },
                new Usuario() { Id = 21, Grupo = "Diretoria", Nome = "José" },
                new Usuario() { Id = 3, Grupo = "RH", Nome = "Camila" },
                new Usuario() { Id = 42, Grupo = "RH", Nome = "Joana" },
                new Usuario() { Id = 102, Grupo = "", Nome = "Joaquim" },
                new Usuario() { Id = 7, Grupo = "RH", Nome = "Camila" },
                new Usuario() { Id = 105, Grupo = "Operações", Nome = "Vitor" }
            };

        /* some non-important codes */

            List<Pessoa> pesssoa = usuarios.ConvertAll(x => new Pessoa
            {
                Nome = x.Nome
            });

            Console.ReadKey();
        }
    }

    class Usuario
    {
        public string Nome { get; set; }
        public int Id { get; set; }
        public string Grupo { get; set; }
    }

    public class Pessoa
    {
        public string Nome { get; set; }
    }
}

但我得到了错误:

错误 CS1061 'List&lt;Usuario&gt;' 不包含 'ConvertAll' 并且没有扩展方法 'ConvertAll' 接受第一个 可以找到类型为“List&lt;Usuario&gt;”的参数(您是否缺少 使用指令还是程序集引用?)

在“ConvertAll”部分。当我在项目中包含“使用 System.Linq”时,可能有什么问题?

【问题讨论】:

  • 测试给定的代码,它没有给出错误
  • @GiladGreen 但是如果这里发生了错误,那么一定是发生了什么
  • 顺便说一下,它与linq无关:它是List&lt;T&gt;的方法
  • 您在.NET Core 项目中工作,.NET Core 中还没有这种方法。
  • 虽然解决方法很简单:List&lt;Pessoa&gt; pesssoa = usuarios.Select(x =&gt; new Pessoa { Nome = x.Nome }).ToList()

标签: c# linq


【解决方案1】:

找出问题所在。当我在 Visual Studio 上创建项目时,我选择了

文件 -> 新建 -> 项目 -> 已安装 -> 模板 -> Visual C# -> 控制台应用程序 (.NET Core)

问题在于选择 Console App (.NET Core)。它似乎没有 Console App (.NET Framework) 那么多的功能。使用 Console App (.NET Framework) 创建新项目后,ConvertAll 运行良好。

【讨论】:

    【解决方案2】:

    您可以为ConvertAll 创建自己的扩展方法:

    public static class ListExts {
        public static List<Tnew> ConvertAll<Told, Tnew>(this List<Told> src, Func<Told, Tnew> fconv) {
            var ans = new List<Tnew>(src.Count);
            for (int j1 = 0; j1 < src.Count; ++j1)
                ans.Add(fconv(src[j1]));
            return ans;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多