I'm stuck on checking a set of lists to see if they have values. I have 8 lists that are created in my program and I need to check if the lists have any values at all. If all 8 lists return values I want to return true. If any of the 8 have no values I want to return false.

Hopefully that makes sense.

Thanks in advance

Recommended Answers

All 3 Replies

What have you tried so far?

Well it is not a very elegant way of doing it but I've tried this.

Keep in mind I've created 8 lists called l_1 through l_8.

List<string> l_true = new List<string>();

            if(l_1.Count < 1)
                l_true.Add("One");

            if(l_2.Count < 1)
                 l_true.Add("Two");

            if(l_3.Count < 1)
                 l_true.Add("Three");

            if(l_4.Count < 1)
                 l_true.Add("Four");

            if(l_5.Count < 1)
                 l_true.Add("Five");

            if(l_6.Count < 1)
                 l_true.Add("Six");

            if(l_7.Count < 1)
                 l_true.Add("Seven");

            if(l_8.Count < 1)
                 l_true.Add("Eight");

           if(l_true.Count == 8)
                 return true;
           else
                 return false;

I know there has to be a better way to do it.

On a second note. I'm trying to print the list of the lists that are missing. Tried this but it doesn't seem to work.

string[] s = l_true.ToArray();
string errorMsg = String.Join(", ", s);

MessageBox.Show("The following lists are empty: " + errorMsg);

Well, here's one way you can do it. I'm not sure on the efficiency in general, but it will clean up the code a little bit and make it look pretty =)

static int main()
{
    List<List<string>> listList = new List<List<string>>();
    
    for(int i = 0; i < numLists; i++)
        listList.Add(new List<string>());
    ...
    if(ListsHaveVals(listList) == "")
        ...
}

private string ListsHaveVals(List<List<string>> listList)
{
    StringBuilder str = new StringBuilder();
    int counter = 0;

    foreach(List<string> li in listList)
    {
        if(li.Count <= 0)
        {
            str.Append(counter.ToString());
        }
        counter++;
    }
    return str.ToString();
}

Not sure if this fits your requirements, but it makes it easier if you need to change the number of lists. This way it will stay dynamic so you can have 3 lists for 40 lists and it will still work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.