2014-05-14 62 views
2

我有一个集合称为ItemCollection看起来像选择项目:如何只从具有特定属性列表设置为true

public class ItemCollection : List<Item> 
{ 
} 

Item有一个名为MyProperty属性:

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

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

现在我只想从我的ItemCollection中获得项目,并将MyProperty设置为true。

我想:

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

不幸的是,Where部分不工作。虽然iItem我得到的错误

无法项目类型隐式转换到ItemCollection。

我如何筛选返回ItemCollection到只包含那些Item S作MyProperty设置为true?

+0

的:

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

所以您得到您的结果部分可能是好的,但返回的值是一个IEnumerable ,不能分配给类型为'ItemCollection'的'ic' –

+0

这是确切的代码?我没有看到任何试图将“Item”转换为“ItemCollection”的东西。 –

+0

该错误似乎表明您正在使用'First','Single'等而不是'Where'。 –

回答

0

扩展功能解决方案太:

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

非常感谢!为什么要使用Dummy? –

+0

为什么要这样做?这是创建一个新对象并运行AddRange '它比使用构造函数创建一个已经初始化的列表的新实例的效率要低很多,对不起,但这不是一个很好的解决方案 –

+0

Dummy类只是一个临时类的名称u可以称之为助手或任何其他类似的东西 –

1

有些答案/评论都提到

(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. 
+0

谢谢。我没有从'List '创建'ItemCollection'的构造函数,但不知道如何制作它。 –

+0

您有权访问ItemCollection类吗?您是否可以修改它? –

+0

是的,我可以。我从来没有做过一个隐式的操作符,但会看看它是否有效!有趣。 编译器说'ItemCollection'需要一个接受一个参数的构造函数。 –

相关问题