开发者

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
                Select开发者_高级运维edLead += 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜