' "-6ren"> ' "-这是一个菜鸟问题。因此,如果我错误地陈述了问题,那是因为我没有完全理解正在发生的事情。 问题 Compile error: Cannot implicitly convert type 'MyClas-6ren">
gpt4 book ai didi

c# - 将可枚举复制到列表? "Cannot implicitly convert type ' MyClass.Items' 到 'System.Collections.Generic.List' "

转载 作者:行者123 更新时间:2023-11-30 21:09:48 24 4
gpt4 key购买 nike

这是一个菜鸟问题。因此,如果我错误地陈述了问题,那是因为我没有完全理解正在发生的事情。

问题

Compile error: Cannot implicitly convert type 'MyClass.Items' to 'System.Collections.Generic.List'

上下文

我正在通过 IOrderedEnumerable 迭代 List,但我无法返回所需的记录,因为它是类型化的 List (因为我的整个应用程序都在来回传递 List 对象)。

我对该方法的输入是一个 List,但当我使用 OrderBy 选项时,它似乎被隐式转换为 IEnumerable

我已经阅读了我找到的所有内容,但似乎都可以归结为:

// ToList is not available!
return SingleItemToCheck.ToList;

// same type conversion error
List<Items> ReturningList = SingleItemToCheck;

问题代码

public static List<Items> FindCheapestItem(List<Items> source)
{
// Now we pop only the first one.
// ISSUE: Sometimes the top entry on the list is bad,
// so we need to check it!
var BestItemCandidate = source.OrderBy(s => s.ItemDesirability);
bool ForgetThisOne = false;

foreach (var SingleItemToCheck in BestItemCandidate)
{
ForgetThisOne = false;

// ... test for ItemDesirability, truncated
if (Desirability < 0)
{
ForgetThisOne = true;
}

if (!ForgetThisOne)
{
// we are just returning the first desirable row
// because we are sorted on desirability
// and consuming code can only digest a single item.
return SingleItemToCheck; // !!! ARGH, compile error !!!
}
}

// means we looped through everything and found nothing of interest
return null;
}

最佳答案

SingleItemToCheck 是单个项目,不是列表。它没有可用的 ToList() 方法。只需创建一个包含单个项目的列表。

return new List<Items> { SingleItemToCheck };

或者,如果您只对其中一项感兴趣,请将方法的返回类型更改为简单的 Items 并完全省略列表。

另一种写法,特别是如果你只对一个项目感兴趣,就是简单地将内部循环逻辑重构为一个函数,然后编写一个查询

return source
.OrderBy(s => s.ItemDesirability)
.Where(s => IsDesirable(s)) // refactored loop logic, returning boolean
.FirstOrDefault(); // first desirable item, or null

否则,如果您绝对需要一个列表,但其中只有一项,请考虑

 var list =  source
.OrderBy(s => s.ItemDesirability)
.Where(s => IsDesirable(s))
.Take(1)
.ToList();

如果没有元素通过,这将是一个空列表。然后您可以选择返回 null,就像您当前的代码所做的那样,或者返回空列表并让调用者处理它而不是 null 结果。

关于c# - 将可枚举复制到列表? "Cannot implicitly convert type ' MyClass.Items' 到 'System.Collections.Generic.List<MyClass.Items>' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8846043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com