I'm pretty fresh when it comes to C#, and I have run into a problem.
I was wondering how I should go about getting data from a List<string[]>
and using it to create objects in a List<MyClass>
?
class FileLoader
{
public FileLoader()
{
if (File.Exists("texter.txt"))
{
List<string> itemSaver = new List<string>();
List<string[]> vectors = new List<string[]>();
StreamReader reader = new StreamReader("texter.txt", Encoding.Default, true);
for (string item = reader.ReadLine(); item != null; item = reader.ReadLine())
{
itemSaver.Add(item);
}
foreach (string a in itemSaver)
{
string[] vektor = a.Split(new string[] { "###" }, StringSplitOptions.None);
vectors.Add(vektor);
}
}
}
}
The textfile has ### as separators, and I need to get the values between them, which is why the Split was done. Now I just need some help figuring out how..
Kind regards.
You need only one for loop :
class FileLoader
{
List<MyClass> myClassList = new List<MyClass>();
public FileLoader()
{
if (File.Exists("texter.txt"))
{
List<string[]> vectors = new List<string[]>();
StreamReader reader = new StreamReader("texter.txt", Encoding.Default, true);
for (string item = reader.ReadLine(); item != null; item = reader.ReadLine())
{
string[] vektor = item.Split(new string[] { "###" }, StringSplitOptions.RemoveEmptyEntries).Select(x=> x.Trim()).ToArray();
vectors.Add(vektor);
MyClass newClass = new MyClass();
myClassList.Add(newClass);
newClass.title = vektor[0];
newClass.type = vektor[1];
}
}
}
}
public class MyClass
{
public string title { get; set; }
public string type { get; set; }
}