如何仅从某个属性设置为true的列表中选择项

本文关键字:true 列表 选择 设置 何仅 属性 | 更新日期: 2023-09-27 18:03:14

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

public class ItemCollection : List<Item>
{
}

Item有一个叫做MyProperty的属性:

public class Item
{
    public bool MyProperty { get; set; }
}

我也有一个ItemManager,它有一个GetItems方法,返回一个ItemCollection

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

我试着:

ItemCollection ic = ItemManager.GetItems().Where(i => i.MyProperty);

不幸的是Where部分不起作用。虽然i指的是Item,但我得到错误

不能隐式地将Item类型转换为ItemCollection。

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

如何仅从某个属性设置为true的列表中选择项

一些答案/评论已经提到

(ItemCollection)ItemManager.GetItems().Where(i => i.MyProperty).ToList()

由于向上转换而无法工作。相反,上面的代码将生成一个List<Item>

下面是使这些工作所需的内容。请注意,您需要能够修改ItemCollection类,以便使其工作。


构造函数

如果你想为ItemCollection类创建一个构造函数,那么下面应该可以工作:

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

要调用构造函数,你可以这样做:

var ic = new ItemCollection(ItemManager.GetItems().Where(i => i.MyProperty));

ItemCollection ic = new ItemCollection(ItemManager.GetItems().Where(i => i.MyProperty));


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

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();