- Home /
how to know when list is empty?
i wanna know when my list has no elements in it. I will add gameObjects to the gameObject list during runtime and i have an if statement that will check current scene index and i also wanna check when this certain list is empty? How should i do?
Answer by GiyomuGames · Sep 28, 2015 at 08:28 AM
If your list is called "myList", then "myList.Count" tells you the number of elements in the list. Therefore "myList.Count == 0" will be true only when your list is empty.
Answer by MadDevil · Sep 28, 2015 at 07:33 AM
Use this :
if(random.Count.Equals(0)) print("List is empty");
As long as you removed the objects from the list when you destroy them then the count will reduce. Otherwise the item will remain in the list and be null.
You can remove null items first with
$$anonymous$$yList.RemoveAll(item => item == null);
Answer by Satsujinken508 · Nov 26, 2016 at 04:37 PM
This is the efficient answer - 'Count' is potentially slow. (If your list is a million items long, then Count will count every single entry, one by one, while 'Any' will just check the first item and then report back immediately.)
And yet... 'Any' doesn't compile for me in Unity:
Type 'System.Collections.Generic.List' does not contain a definition for `Any' and no extension method 'Any' of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)
So is there a 'using' directive that will make this work?
using System.Linq;
Also, if you don't know which directive it is, you can just find it in msdn aswell)
A note to "'Count' is potentially slow.":
.
In the description of Count (https://msdn.microsoft.com/en-us/library/27b47ht3(v=vs.110).aspx) it is stated that: "Retrieving the value of this property is an O(1) operation."
.
In other words, finding the number of elements in a list does not require counting the list's elements. The number of elements in the list is kept in the list class and is incremented or decremented as you add or remove elements, then when you use Count this number is simply retrieved. Because of this Count is equally fast regardless of the number of elements in your list.
.
To summarize: count is likely the most efficient way to check if a list is empty (even if the list you check has millions of elements).
That's definitely a clean way to check that the list is empty. I will just point out that a Field Engineer in Unity explained in a conference about optimization that one should never ever use Linq at runtime because it is super slow. It's just FYI, for simple games it will probably be unnoticeable!
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How to remove objects from a list ? 3 Answers
Can't add GameObjects to ArrayList 1 Answer
Keep adding targets to a list 2 Answers
Get first gameobject in a list and cycle through on keypress 1 Answer