public void FindClosestEnemy()
{
List<GameObject> pList = GameObject.FindGameObjectsWithTag("Player");
pList.OrderBy(obj=>Vector3.Distance(FindLocalPlayer().transform.position,
obj.transform.position)).ToList();
}
I do not understand the difference between the two lists. How do I convert the 'UnityEngine.GameObject[]' list to the System.Collections.Generic.List>UnityEngine.GameObject<
GameObject.FindGameObjectsWithTag returns an array of GameObjects.
An array in C# is a data structure that stores multiple objects of the same type.
A list is a generic collection of objects.
While an array and a list are very similar in concept, there are different between the two in terms of data access and usage. Generally an array is only populated once at creation and only read thereafter, while a List can have it's elements altered at any time (some caveats apply).
This StackOverflow question summaries why you might want one over the other: Array versus List<T>: When to use which?
In your specific case, you want to apply some Linq ordering to your GameObject collection so you need to convert the array received from FindGameObjectsWithTag to a list.
You can do this in several ways. The easiest is to use a constructor overload on list to assign the entire array at once:
GameObject[] gameObjectArray = GameObject.FindGameObjectsWithTag("Player");
List<GameObject> gameObjectList = new List<GameObject(gameObjectArray);
Some other options are available here: Conversion of System.Array to List
As Steve rightly explain but i want to answer in a bit different manner:
Actually in your code you are assigning array type object (GameObject.FindGameObjectsWithTag("Player")) into list type (List<GameObject> pList ) object which is not implicitly support by the compiler. You have to convert your list into an array type:
List<GameObject> pList = new List<GameObject>(GameObject.FindGameObjectsWithTag("Player"));
After this, you will be able to use your code.
Now for the first part of the question
I do not understand the difference between the two lists.
Actually you are asking about Different b/w array and list and the main difference you should need to keep in mind that when you have fixed length of data then, you should use array and if you have variable lenght of data then you use List.
You can also find great detail on this topic on stackoverflow
Array versus List: When to use which?
How and when to abandon the use of arrays in C#?
Why do we use arrays instead of other data structures?
List explaniation by MSDN
Arrays considered somewhat harmful
Should I user array or list
Related
I have a quick question (this is in C#). Let's say I have an array of numbers:
int[] count = new int[4] {0, 4, 3, 2};
I have a method that does some stuff:
public void Invert(int[] arrayVar)
{
for (int i = 0; i < arrayVar.Count; i++)
{
//arrayVar[i] = stuff
}
}
If I call the method by doing this:
Invert(count);
Is there a way to have the method directly edit the count array instead of just duplicating it and editing the duplicate? I can't have a global variable for multithreading reasons and I can't return the end result because I have similar methods that have to return very specific things. Is this possible? Thanks!
Is there a way to have the method directly edit the count array instead of just duplicating it and editing the duplicate?
Yes. Do exactly what you are doing. Your program already does exactly what you are asking for.
Arrays are passed by reference in C#. count and arrayVar refer to the same array. When you pass an array to a method, that method does not get a copy of the array. It gets a copy of a reference to the array.
Changes that you make to arrayVar inside Invert will also be made to count inside the caller because those two variables both contain a reference to the same array.
Do not confuse this with the ref feature of C#. Ref makes two variables act as though they are the same variable. Here you have two different variables that both refer to the same array. Make sure that the distinction is clear in your mind.
A number of answers confusingly suggest that you use a list instead of an array. Lists are also reference types; they have the same semantics as arrays when passed to a method. That is, the passed-in value is a reference. The reason to use a list instead of an array is because lists are more flexible and powerful than arrays. Arrays are fixed in size; an array with ten elements always has ten elements. A list can have new elements added or old elements removed.
Simple old school C# question: Is an ArrayList an Array or a List? The differences between the two are enormous, so I'm curious if anyone knows the way that ArrayLists store data?
ArrayList behaves like a list (in particular, its count of elements can grow, unlike an array), but it's backed by an array, which will be dynamically resized as needed. Hence the name ArrayList.
Things that behave like lists don't have to be backed by arrays (they could be linked lists, for example), but ArrayList is.
.NET Framework contains a data structure that provides this functionality—the System.Collections.ArrayList classThe ArrayList maintains an internal object array and provides automatic resizing of the array as the number of elements added to the ArrayList grows. Because the ArrayList uses an object array, developers can add any type—strings, integers, FileInfo objects, Form instances, anything.
While the ArrayList provides added flexibility over the standard array, this flexibility comes at the cost of performance. Because the ArrayList stores an array of objects, when reading the value from an ArrayList you need to explicitly cast it to the data type being stored in the specified location. Recall that an array of a value type—such as a System.Int32, System.Double, System.Boolean, and so on—is stored contiguously in the managed heap in its unboxed form. The ArrayList's internal array, however, is an array of object references. Therefore, even if you have an ArrayList that stores nothing but value types, each ArrayList element is a reference to a boxed value type.
you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.
Apart from other differences, one more difference is that ArrayList are not strongly typed i.e array list can add any type of element which is derived from object as shown in the code below
ArrayList myArrayList = new ArrayList();
myArrayList.Add(1);
myArrayList.Add("test");
but array and IList are strongly typed i.e we can take advantage of compile type checking in both of them e.g
int[] myarray = new int[5];
myarray[0] = 1; // This is correct
myarray[1] = "test"; // compile time error
Is there any established way of returning a read-only 2-d array in C#?
I know ReadOnlyCollection is the right thing to use for a 1-d array, and am happy to write my own wrapper class that implements a this[] {get}. But I don't want to reinvent the wheel if this wheel already exists.
Unfortunately there is no any built-in implementation to handle a case you ask for.
But a simple implementation on your own, shouldn't be something difficult.
The only think, I hope you aware of it, that you will do is a readonly collection, but not elements inside that collection.
Hope this helps.
There's only one way to simulate this.
You need to create your own class, with a private array.
The most similar implementation of an array is an indexer:
Using indexers
Indexers (C# programming guide)
10.8 Indexers (old)
C# 6.0 draft Indexers
The '10.8' link shows the simulation of a bidimensional array.
If you implement the indexer only with a getter, the user can only read the elements, but not write them. However, if each element is an object (reference type) you can't prevent the modification of the accessed objects properties.
However, there are several ways of simulating "read-only" objects:
Create a wrapper class that exposes the properties of each element in the array as read only properties, so that they cannot be modified
Using primitive value types (like int)
Defeating the changes by returning a copy of the element in the private array instead of the original element in the private array, so that, the changes made to the object don't affect the original object in the array.
In other languages like C++ there are references and pointers to constant values, but this doesn't exist in C#.
I have a class that's going to hold 3 parallel arrays. (For a class assignment we're basically coding a rudimentary xml parser...beginning programming class)
*Note, I'm doing this in very basic OOP. I've got an XMLObject class which has the arrays, and holds the xml elements in one array, the data values in another, and the ending elements in the third. I've also got an XMLParse object that does the actual parsing, and stores the strings to their various arrays as it finds them. I've been forbiddin from using .net's xml stuff for this assignment, has to be a byte by byte read in.
Now I was reading on MSDN about indexers, and as I understand it, I can either only have one array using an indexer(since that's the only way for properties to receive parameters), or I have to make my arrays public so that the parse class can add to them, and main or another class can read from them.
Do I have that right or am I missing something/not understanding how to get and set arrays of one class from another?
Does the same go for list as well?
If I understand your question you want to have many indexers on your class which will return the various elements from the arrays that the class holds.
you can have many indexers, but only if the type used by each indexer is different. So you could have an indexer by int and an indexer by string, but not 2 indexers by int.
From the sounds of things you won't be able to use indexers to access all the values your class holds, as they will probably all want to use int.
Publicly exposing the arrays is one option, but you could also provide different methods for reading each thing, so you could have GetXmlElement(int index), GetDataValue(int index) and GetEndingElement(int index) to provide access to the contents of the arrays.
Another option would be to store the data in arrays internally, but accept and return a class which bundled up all the data together. This way you could have a single indexer which returned all the data, as all the data would be a single object with the element, data value and end element in it.
you would have to provide similar methods for adding data and potentially removing and changing as well. Whether you want to do this, opr just exopse the underlying arrays/lists depends on if you want to be able to exercise control over the adding/accessing/deleting/changing of the arrays or not.
I suggest you use List<T> instead of array for storing the data. It is much easier to work with.
See here.
This question already has answers here:
Array versus List<T>: When to use which?
(16 answers)
Closed 9 years ago.
i basically want to know the differences or advantages in using a generic list instead of an array in the below mentioned scenario
class Employee
{
private string _empName;
public string EmpName
{
get{ return _empName; }
set{ _empName = value; }
}
}
1. Employee[] emp
2. List<Employee> emp
can anyone please tell me the advantages or disadvantages and which one to prefer?
One big difference is that List<Employee> can be expanded (you can call Add on it) or contracted (you can call Remove on it) whereas Employee[] is fixed in size. Thus, Employee[] is tougher to work with unless the need calls for it.
The biggest difference is that arrays can't be made longer or shorter once they're created. List instances, however can have elements added or removed. There are other diffs too (e.g. different sets of methods available) but add/remove is the big difference.
I like List unless there's a really good reason to use an Array, since the flexibility of List is nice and the perf penalty is very small relative to the cost of most other things your code is usually doing.
If you want to dive into a lot of interesting technical detail, check out this StackOverflow thread which delves into the List vs. Array question in more depth.
With the generic list, you can Add / Remove etc cheaply (at least, at the far end). Resizing an array (to add/remove) is more expensive. The obvious downside is that a list has spare capacity so maybe wastes a few bytes - not worth worrying about in most cases, though (and you can trim it).
Generally, prefer lists unless you know your data never changes size.
API-wise, since LINQ there is little to choose between them (i.e. the extra methods on List<T> are largely duplicated by LINQ, so arrays get them for free).
Another advantage is that with a list you don't need to expose a setter:
private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items { get { return items; } }
eliminating a range of null bugs, and allowing you to keep control over the data (especially if you use a different IList<> implementation that supports inspection / validation when changing the contents).
If you are exposing a collection in a public interface the .NET Framework Guidelines advise to use a List rather than T[]. (In fact, a BindingList< T >)
Internally, an array can be more appropriate if you have a collection which is a fixed, known size. Resizing an array is expensive compared to adding an element to the end of a List.
You need to know the size of an array at the time that it is created, but you cannot change its size after it has been created.
So, it uses dynamic memory allocation for the array at creation time. (This differs from static memory allocation as used for C++ arrays, where the size must be known at compile time.)
A list can grow dynamically AFTER it has been created, and it has the .Add() function to do that.
-from MSDN
Generics Vs Array Lists-SO General comparision.
Generic List vs Arrays-SO Why is generic list slower than array?
Which one to prefer? List<T>.
If you know the number of elements array is a good choice. If not use the list. Internally List<T> uses an array of T so the are actually more like than you may think.
With a List, you don't need to know the size of the array beforehand. You can dynamically add new Employee's based on the needs of your implementation.