【问题标题】:How to combined the itemList to single line?如何将项目列表合并为单行?
【发布时间】:2017-06-10 04:13:42
【问题描述】:

我希望我的流派结合在一起,而不是在 diff 行中打印。 我如何加入我的流派加入,比如“动作,冒险”而不是打印成两条差异线? 我的输出打印在两个不同的行中。 抱歉格式和英语不好。

我的代码:

    static void initMovies(List<Movie> mList)
    {
        Movie m;

        
        m = new Movie("The Great Wall", 103, "NC16", new DateTime(2016,12,29),new List<string> { "Action", "Adventure" });
        mList.Add(m);


        m = new Movie("Rogue One: A Star Wars Story", 134, "PG13", new DateTime(2016,12,15),new List<string> { "Action","Adventure"});
        mList.Add(m);


        m = new Movie("Office Christmas Party", 106, "M18", new DateTime(2017,01,15),new List<string> { "Comedy" });
        mList.Add(m);

        m = new Movie("Power Rangers", 120, "G",new DateTime(2017,1,31),new List<string>{ "Fantasy","Thriller"});
        mList.Add(m);
    }
  

 
static void displayMovie(List<Movie> mList)
{ 
    Movie m;
    Console.WriteLine("{0,-10} {1,-30} {2,-10} {3,-20} {4,-20} {5,-10}","No","Title","Duration","Genre","Classification","Opening Date");
    var gList = new List<List<string>>();
    for(int i = 0; i<mList.Count;i++)
    {
        m = mList[i];
        foreach (string value in m.GetGenreList())
        {
            Console.WriteLine("{0,-10} {1,-30} {2,-10} {3,-20} {4,-20} {5,-10}", i + 1, m.Title, m.Duration, value, m.Classification, m.openingDate);
        }
    }
}

示例:

我的输出:

【问题讨论】:

  • 在此处发布图像而不是示例数据或输出的文本被认为是非常粗鲁的。
  • 什么 tgt ?你能添加你的数据文本吗
  • 请分享样本数据,以便我们轻松测试。 :)
  • 这样更好吗?
  • 文本中的电影列表怎么样?

标签: c# list oop join


【解决方案1】:

您必须使用string.join 连接从 GetGenreList() 方法获得的元素并省略内部 foreach 循环,如下所示:

for (int i = 0; i < mList.Count; i++)
{
    m = mList[i];
    //foreach (string value in m.GetGenreList())
    //{
        string all_genres = string.Join(",", m.GetGenreList()); //get all genres as a comma seperated in single string
        Console.WriteLine("{0,-10} {1,-30} {2,-10} {3,-20} {4,-20} {5,-10}", i + 1, m.Title, m.Duration, all_genres, m.Classification, m.openingDate);
    //}
}

【讨论】:

    【解决方案2】:

    我认为您应该只删除内部 foreach 并在此处使用 string.Join

    这是一个例子:

    static void displayMovie(List<Movie> mList)
    { 
        Movie m;
        Console.WriteLine("{0,-10} {1,-30} {2,-10} {3,-20} {4,-20} {5,-10}","No","Title","Duration","Genre","Classification","Opening Date");
        var gList = new List<List<string>>();
        for(int i = 0; i<mList.Count;i++)
        {
            m = mList[i];
                string genres = string.Join(", ", m.GetGenreList().ToArray());
                Console.WriteLine("{0,-10} {1,-30} {2,-10} {3,-20} {4,-20} {5,-10}", i + 1, m.Title, m.Duration, genres, m.Classification, m.openingDate);
            }
        }
    }
    

    结果:

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2011-01-17
      • 2011-10-23
      • 2016-04-03
      • 1970-01-01
      • 2022-08-23
      相关资源
      最近更新 更多