2014-05-14 58 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'需要一個接受一個參數的構造函數。 –

相關問題