简体   繁体   中英

Is it possible to get the item count of a List<T> when T is different?

I have a subroutine that changes its operation slightly to include either one list or the other then perform the same operation. Since it is just counting the number of items in the list, I figure there is probably an easy way to get the item count regardless of the list type.

Thanks in advance!

EDIT:

private List<Message> currentMessages;
private List<Lead> currentLeads; 
...
private void nextLeadBtn_Click(object sender, EventArgs e)
    {
        object temp;
        if (includeAllCheck.Checked)
        {

            temp = currentMessages;
            if (SelectedLead == (currentMessages.Count - 1))
                SelectedLead = 0;
            else
                SelectedLead += 1;
        }
        else
        {
            temp = currentLeads;
            if (SelectedLead == (currentLeads.Count - 1))
                SelectedLead = 0;
            else
                SelectedLead += 1;  
        }
        // This is what I want to replace the above with
        //if (SelectedLead == ((List)temp).Count - 1) //obviously this does not work
        //    SelectedLead = 0;
        //else
        //    SelectedLead += 1;




        LoadPreviews(includeAllCheck.Checked);
    }

You can always use ICollection.Count , if you don't want to deal with generics. List<T> implements ICollection , so you can always access that.

EDIT: So now that you've posted your code, you can just change the line:

if (SelectedLead == ((List)temp).Count - 1)  // won't compile, of course

to

if (SelectedLead == ((ICollection)temp).Count - 1)  // happy as a clam

In fact, an even better option would be to change the declaration of object temp to ICollection temp to better convey the type information, and avoid all of this casting nonsense altogether.

ICollection temp;
        if (includeAllCheck.Checked)
        {

            temp = currentMessages;            
        }
        else
        {
            temp = currentLeads;

        }
if (SelectedLead == (temp.Count - 1))
                SelectedLead = 0;
            else
                SelectedLead += 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM