Stoopkid
Stoopkid

Reputation: 1955

Add ListView objects to an array

Is there a way to add ListView objects to an array so that I can address them quickly with a for loop?

    public static ListView tagListView;
    public static ListView commonListView;
    public static ListView recentListView;
    public static ListView[] listviews = { tagListView, commonListView, recentListView };

This code results in the listviews array items being null. I have tried a few variations of this with the same results. Is this possible to do? It seems like I just need to make an array of pointers to these three objects.

I am trying to do this because the ListViews are for the most part very different and having the names makes it much more readable than just having three items in an array but every once in a while I need to do the same thing to all three.

Upvotes: 0

Views: 66

Answers (2)

Enigmativity
Enigmativity

Reputation: 117055

Your code, as it stands, is effectively this:

public static ListView tagListView = null;
public static ListView commonListView = null;
public static ListView recentListView = null;

So your array assignment is really doing this:

public static ListView[] listviews = { null, null, null};

If you can instantiate the three list views first then that would be your best approach.

However, if you can't do that and need to instantiate them later in your code then there is another approach.

You could do this:

public static IEnumerable<ListView> listviews = (new Func<ListView>[]
{
    () => tagListView,
    () => commonListView,
    () => recentListView,
}).Select(x => x()).Where(x => x != null);

Now you have an enumerable of your instantiated list views, at the time you iterate the enumerable.

Upvotes: 0

Mike Hixson
Mike Hixson

Reputation: 5189

You almost got it. You just need to instantiate the ListViews.

   public static ListView tagListView = new ListView();
   public static ListView commonListView = new ListView();
   public static ListView recentListView = new ListView();
   public static ListView[] listviews = { tagListView, commonListView, recentListView };

Upvotes: 1

Related Questions