Reputation: 23
using System;
using System.IO;
using System.Text;
public class Movies
{
public string moviename { get; set; }
public int cast { get; set; }
public string[] castmember { get; set; }
public override string ToString()
{
return string.Format("Movie: {0} \nCast #: {1} \nCast Member: {3}",
moviename.ToString(),
cast,
castmember.ToString());
}
}
public class MovieData
{
public int NumberOfLines = 0;
public string UserInput;
public void ManageData()
{
string[] text = File.ReadAllLines("@File Path");
NumberOfLines = text.GetUpperBound(0);
Movies[] movies = new Movies[NumberOfLines];
int i = 0;
foreach (string line in text)
{
movies[i] = new Movies();
movies[i].moviename = Convert.ToString(line.Trim());
movies[i].cast = Convert.ToInt32(line.Trim());
int ii = movies[i].cast;
//Here I want to create a movies[i].castmember[ii] with ii being the length
}
I am trying to store data that is basically in line format, but there is a particular set of lines that would be more logical to store in an array. How would I go about creating a movies[i].castmember array with length of ii (cast)?
Upvotes: 0
Views: 325
Reputation: 12567
var moviesCollection = new Collection<Movie>();
var movie = new Movie();
// for each movie...
moviesCollection.Add(movie);
// if you use System.Linq you can convert any IEnumerable<T> to array
// by calling ToArray()
movies = moviesCollection.ToArray();
And you can follow the same principle for adding cast members to the movie.
Upvotes: 0
Reputation: 35716
Wouldn't this be a simpler approach?
var movies = File.ReadAllLines("@FilePath").Select(line =>
new Movies
{
moviename = line.Trim(),
cast = Convert.ToInt32(line.Trim()),
castmember = new string[Convert.ToInt32(line.Trim())]
});
I have a number of concerns with the code you have posted. For instance, how can the same line
represent a name and define the cast size at the same time? Why does your class Movies
that represents a single movie have a plural name?
At the risk of spoon feeding you, should your code be more like this?
using System;
using System.IO;
using System.Text;
public class Movie
{
public string Name { get; set; }
public IList<string> Cast { get; set; }
public override string ToString()
{
var s = new StringBuilder();
s.AppendFormat("Movie: {0}", this.Name);
s.AppendLine();
for (var i = 0; i < this.Cast.Count; i++)
{
s.AppendFormat(
" Cast #:{0}, Member: {1}",
i + 1,
this.Cast[i]);
s.AppendLine();
}
return s.ToString();
}
}
public class MovieData
{
public void MovieData(string filePath)
{
this.Movies = File.ReadAllLines(filePath).Select(line =>
new Movie
{
// Something here that makes sense.
});
}
public IList<Movie> Movies { get; private set; }
}
Upvotes: 0
Reputation: 7629
I can notice some errors on your code.. for example you are converting the same line.Trim()
value into string
and Int32
but this is not the question..
I think you are asking how to create an array of ii
elements..that's it:
movies[i].castmember = new string[ii];
Upvotes: 1