0
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


}

我正在尝试存储基本上以行格式的数据,但是有一组特定的行将更合乎逻辑地存储在数组中。我将如何创建一个长度为 ii (cast) 的 movies[i].castmember 数组?

4

3 回答 3

1

我可以注意到您的代码中有一些错误..例如,您将相同的line.Trim()值转换为stringInt32但这不是问题..

我想你在问如何创建一个ii元素数组..就是这样:

movies[i].castmember = new string[ii];
于 2012-12-10T09:27:15.787 回答
0

这不是更简单的方法吗?

var movies = File.ReadAllLines("@FilePath").Select(line =>
    new Movies
        {
            moviename = line.Trim(),
            cast = Convert.ToInt32(line.Trim()),
            castmember = new string[Convert.ToInt32(line.Trim())]
        });

我对您发布的代码有很多担忧。例如,同一个名称如何同时line代表一个名称并定义演员表大小?为什么Movies代表一部电影的类有复数名称?


冒着勺子喂你的风险,你的代码应该更像这样吗?

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; }
}
于 2012-12-10T09:28:26.740 回答
0
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();

您可以遵循相同的原则将演员添加到电影中。

于 2012-12-10T09:28:27.433 回答