如何仅从某个属性设置为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
?
一些答案/评论已经提到
(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();