Question

I have a Collection called ItemCollection that looks like:

public class ItemCollection : List<Item>
{
}

The Item has a property called MyProperty:

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

I also have a ItemManager that has a GetItems method which returns an ItemCollection.

Now I want to only get items from my ItemCollection with MyProperty set to true.

I tried:

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

Unfortunately the Where part does not work. Although i refers to an Item I get the error

Cannot implicitly convert type Item to ItemCollection.

How can I filter the returned ItemCollection to only contain those Items that have MyProperty set to true?

Was it helpful?

Solution 2

Extension functions are Great solution too :

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

So you get your result by:

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

OTHER TIPS

Some of the answers/comments have mentioned

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

which will not work because of up-casting. Instead, the above will produce a List<Item>.

The following is what you will need to make these work. Note that you will need to have the ability to modify the ItemCollection class in order for this to work.


Constructor

If you would like to make a constructor for the ItemCollection class, then the following should work:

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

To call the constructor, you would then do the following:

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

or

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


Note about the error message

In the comments, when asked to change ItemCollection ic = ItemManager.GetItems..... to var ic = ItemManager.GetItems..... and then tell us what the type of ic is, you mentioned that you got Systems.Collections.Generic.List<T> which would translate to List<Item>. The error message that you received was actually not the error message that you should have received, which is likely just due to the IDE being confused, which occasionally happens when there are errors on the page. What you should have received is something more along the lines of:

Cannot implicitly convert type IEnumerable<Item> to ItemCollection.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top