c# - 无法从用法中推断出方法 '' 的类型参数。尝试明确指定类型参数

标签 c# linq

在做这个的时候

IEnumerable<Colors> c = db.Products.Where(t => t.ProductID == p.ProductID).SelectMany(s => s.Colors);
if (c.Any()) sp.color = Constructor(c);

以后

private string Constructor<T>(List<T> list)
{
     //Do something
}

我得到了错误

The type arguments for method 'Controller.Constructor(System.Collections.Generic.List)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

当然是不对的。但是我错过了什么?

最佳答案

Constructor<T>()您期望的方法 List<T>类型,但您提供了 IEnumerable<T> 的实例.

  • 将方法参数类型更改为IEnumerable<T>
  • 将查询转换为 List<T>类型
IEnumerable<Colors> c =
    db
        .Products
        .Where(t => t.ProductID == p.ProductID)
        .SelectMany(s => s.Colors)
        .ToList();

if (c.Any()) sp.color = Constructor(c);

private string Constructor<T>(IEnumerable<T> list)
{
    //Do something
}

关于c# - 无法从用法中推断出方法 '' 的类型参数。尝试明确指定类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829132/

相关文章:

c# - 对象列表上的 InvalidCastException

c# - 如何从非泛型函数返回泛型函数?

c# - 更改我的对象列表上的顺序

c# - 如何使用 LINQ 使用不同的分隔符将字符串拆分两次?

c# - 如何区分不同的值(value)观?

C#/LINQ : Trying to optimize performance

javascript - 从 Razor 代码中使用 javascript/jquery

c# - 使用 where 语句的 LINQ 非常慢

c# - 如何在 C# 中使用 LINQ 从字典中删除项目

c# - 使用左连接和 sum() 的 Linq To SQL 抛出异常