0

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.

1
  • 4
    You haven't instantiated the three variables that you are adding to the array. That's why they are null. Commented Jun 24, 2014 at 3:47

2 Answers 2

1

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 };
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, sorry, I failed to mention that these three ListViews are assigned in a different part of my code to actual ListViews on my form.
Can you show the code for the problem you are dealing with?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.