- Home /
Need help with converting an array to a list in C#`
Okay, I'm bringing in xml data, so I assume that has to be done with an array, or at least is done that way in this example: http://wiki.unity3d.com/index.php?title=Saving_and_Loading_Data:_XmlSerializer . Now since that part works, I don't want to mess around with it unless I have to, I need to convert deck information brought in from an array into a list, so it's easier to manipulate. Here is the bit of code that is given me an issue:
var deck = DeckContainer.Load(Path.Combine(Application.dataPath, "kdeck.xml"));
int test = deck.Dcards [0].Number;
Debug.Log (test);
int numofCards = deck.Dcards.Length;
Dcard tempcard;
Debug.Log (numofCards);
for (int c = 0; c < numofCards; c++) {
tempcard = deck.Dcards[c];
playerdeck.Insert(c,tempcard);
tempcard = playerdeck[c];
Debug.Log (tempcard);
}
please note that the playerdeck list is a Dcard list so that isn't the problem. I keep the getting this error:
`NullReferenceException: Object reference not set to an instance of an object now tempcard is a Dcard object, so I'm not quiet sure what's going on here. Note also you can't tell this from here, but deck.Dcards[] does hold Dcard objects. I can access the Dcard properties like this deck.Decards[0].Number and such, as defined in my Dcard class. Any ideas?
Answer by MakeCodeNow · Mar 09, 2014 at 04:17 AM
You can do either one of these:
List<> someList = new List(someArray);
or
someList.AddRange(someArray);
Answer by dakkuuan · Mar 10, 2014 at 09:18 PM
I found a solution as well, somelist = somearray.ToList (); with using System.Linq;
Answer by Master109 · Nov 05, 2018 at 05:45 PM
using System.Collections.Generic;
// namespace Extensions
// {
public static class CollectionExtensions
{
public static List<T> ToList<T> (this T[] array)
{
List<T> output = new List<T>();
output.AddRange(array);
return output;
}
}
// }
Answer by solidearthvr · Sep 26, 2017 at 11:18 PM
Here's a good example:
using System.Linq;
using System.Collections.Generic;
private void FindObjsMatchingPattern(string name) {
List<GameObject> objs = GameObject.FindObjectsOfType<GameObject>().Where(obj => obj.name.Contains(name)).ToList();
foreach (var go in objs)
{
Debug.LogFormat("found: {0}", go.name);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Query with C# arrays and List<> 2 Answers
A node in a childnode? 1 Answer
How to modify array values? 1 Answer
Distribute terrain in zones 3 Answers