ListBox GetSelectedIndices Count vs Length

938 views Asked by At

In my web application, I created a ListBox that is populated with a list of items. I have been doing some research and discovered that I can count the number of selected items with the code below in my IF statement.

Using C#, aspx

If (ListBox1.GetSelectedIndices().Count() > 0) {
//do something
}
else { //do something else
}

I have also discovered another property called Length, which seems to do the same exact thing.

If (ListBox1.GetSelectedIndices().Length > 0) {
//do something
}
else { //do something else
}

Is there any difference between the 2? Both seem to satisfy my condition in how I am use it, but not sure if 1 way is better/faster than the other, etc.. Any input is appreciated. Thanks.

2

There are 2 answers

0
COLD TOLD On BEST ANSWER

I think that ListBox inherits or implements Enumerable that has an option to return Count the number of elements in the list.

The ListBox also has it own method called .Length which has a similar effects but specifically used in the class ListBox

If I would have to choose between two I would go with Lenght

0
AudioBubble On

Count() is an extension method added from the System.Linq namespace, and is - generally speaking - much slower than the Length property for types that have it, because it has to enumerate the entire collection first. It's ideal to use Length when you can. GetSelectedIndecies() just returns an array in ASPX, so the Count() method is quite unnecessary in this instance.