C#在一个对象数组中创建一个数组

时间:2012-12-10 09:12:44

标签: c#

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(演员)的电影[i] .castmember数组?

3 个答案:

答案 0 :(得分:1)

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

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

movies[i].castmember = new string[ii];

答案 1 :(得分: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; }
}

答案 2 :(得分: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();

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