C# 如何仅从某些属性设置为true的列表中选择项目

C# 如何仅从某些属性设置为true的列表中选择项目,c#,linq,C#,Linq,我有一个名为ItemCollection的集合,看起来像: public class ItemCollection : List<Item> { } 我还有一个ItemManager,它有一个GetItems方法,返回一个ItemCollection 现在我只想从ItemCollection中获取MyProperty设置为true的项目 我试过: ItemCollection ic = ItemManager.GetItems().Where(i => i.MyPropert

我有一个名为
ItemCollection
的集合,看起来像:

public class ItemCollection : List<Item>
{
}
我还有一个
ItemManager
,它有一个
GetItems
方法,返回一个
ItemCollection

现在我只想从
ItemCollection
中获取
MyProperty
设置为true的项目

我试过:

ItemCollection ic = ItemManager.GetItems().Where(i => i.MyProperty);
不幸的是,
,其中
部分不工作。虽然
i
引用了
但我得到了错误

无法将类型项隐式转换为ItemCollection


我如何过滤返回的
ItemCollection
以仅包含那些
MyProperty
设置为true的
Item

(ItemCollection)ItemManager.GetItems().Where(i => i.MyProperty).ToList()
因为向上浇铸,这将不起作用。相反,上面将生成一个
列表

以下是使这些工作正常进行所需的内容。请注意,您需要能够修改
ItemCollection
类才能使其工作


构造函数

如果您想为
ItemCollection
类创建构造函数,那么以下操作应该有效:

public ItemCollection(IEnumerable<Item> items) : base(items) {}


有关错误消息的注意事项

在评论中,当要求将
ItemCollection ic=ItemManager.GetItems….
更改为
var ic=ItemManager.GetItems….
然后告诉我们
ic
的类型时,您提到您得到了
Systems.Collections.Generic.List
,这将转换为
List
。您收到的错误消息实际上并不是您应该收到的错误消息,这可能只是由于IDE被混淆了,这在页面上出现错误时偶尔会发生。您本应收到的是以下内容:

Cannot implicitly convert type IEnumerable<Item> to ItemCollection.
无法将类型IEnumerable隐式转换为ItemCollection。

扩展功能也是非常好的解决方案:

public static class Dummy { 
    public static ItemCollection ToItemCollection(this IEnumerable<Item> Items)
    {
        var ic = new ItemCollection();
        ic.AddRange(Items);
        return ic;
    }
}

where部分可能正常,但返回的值是IEnumerable,不能分配给
ic
,它属于
ItemCollection
类型,这是确切的代码吗?我没有看到任何东西试图将
项目
转换为
项目集合
。错误似乎表明您正在使用
第一个
单个
等。而不是
其中
@KendallFrey No,实际上代码更复杂(太多,无法在此发布),但是我看不出问题是什么。在这种情况下,您应该用一些更简单的代码重现问题。当代码和错误消息不匹配时,很难诊断问题。谢谢。我还没有从
List
创建
ItemCollection
的构造函数,也不知道如何创建它。您有权访问
ItemCollection
类,并且可以修改它吗?是的,我可以。我从来没有做过隐式运算符,但会看看它是否有效!有趣。编译器说,
ItemCollection
需要一个接受一个参数的构造函数。或者,您是否能够修改显式使用ItemCollection的方法?(在某些情况下,它们可能会被重构,以
IEnumerable
作为参数)@Katana314是的,但是有很多方法使用
ItemCollection
,所以我更喜欢使用这个方法。使用它感觉更干净。你为什么要这样做?这就是创建一个新对象并在其上运行
AddRange
,这比仅使用构造函数创建已初始化列表的新实例效率要低得多。很抱歉,这不是一个很好的解决方案。Dummy类只是一个临时类的名称,你可以像Helper这样称呼它。无法让它工作。它说IEnumerable不包含
ToItemCollection
的定义。我对
Where
没有问题,对
ToList
没有问题,对创建新实例也没有问题。我在没有任何押韵或理由的情况下调用
AddRange
时遇到问题。“最佳实践”一词在这里是完全没有意义的,因为这绝不是、形成或形成“最佳实践”,也不是在任何地方定义的。我也不知道你为什么提到
ToList
,因为你没有在分机中的任何地方调用它,也没有调用分机。在我的情况下,@ZacharyKniebel的代码是有效的,而@ZacharyKniebel的代码是无效的。我接受这个答案。这可能是我的代码中的某些内容,或者是因为。不管怎样,我从这两方面都学到了很多!谢谢
ItemCollection ic = new ItemCollection(ItemManager.GetItems().Where(i => i.MyProperty));
Cannot implicitly convert type IEnumerable<Item> to ItemCollection.
public static class Dummy { 
    public static ItemCollection ToItemCollection(this IEnumerable<Item> Items)
    {
        var ic = new ItemCollection();
        ic.AddRange(Items);
        return ic;
    }
}
ItemCollection ic = ItemManager.GetItems().Where(i => i.MyProperty).ToItemCollection();