使用 TextWriter 编写自定义列表

Writing custom list using TextWriter

我有一个 class Author.cs 作为:

public class Author  
{  
   public Author()  
   { }  

   public int AuthorID;  
   public string AuthorName;  
   public List<Papers> Papers;  

   // ... rest of the methods...  
}  

和另一个 class Paper.cs 作为:

public class Paper  
{  
   public Paper()
   { }

   public int PaperID { get; set; }
   public List<int> CoAuthors { get; set; }
   public int VenueID { get; set; }
   public int PaperCategory { get; set; }
   public int Year { get; set; }  
}  

我尝试在文本文件中打印为:

TextWriter twObjClus = File.CreateText(Path.Combine(path, objClusterFilename));  
foreach (CurrentCluster curCluster in curClusters)
{
   twObjClus.WriteLine(@"ClusterID: {0}, ClusterSize: {1} \n",  
                         curCluster.GetClusterID(), curCluster.GetClusterSize()  
                      );
   twObjClus.WriteLine("--------------------------------------------------------------");  

   foreach (EvoObject eEvoObject in curCluster.GetClusterObjects())
   {
      Author eAuthor = (Author)eEvoObject.GetOriginalObject(); // it gives Object ID

      twObjClus.WriteLine(@"AuthorID: {0}, AuthorName: {1}, PaperID: {2}, Year: {3} \n",  
                            eAuthor.AuthorID, eAuthor.AuthorName,  
                            eAuthor.Papers.Select(p => p.PaperID),  
                            eAuthor.Papers.Select(y => y.Year)  
                         );
   } 
   twObjClus.WriteLine("\n\n");
}
twObjClus.Flush();
twObjClus.Close();  

我在文本文件中正确打印 Author_IDAuthor_Name,但没有打印 Paper_IDYear,而这两个值,语句在文本文件中打印的是:

System.Linq.Enumerable+WhereSelectListIterator`2[DirichletProcessClustering.GraphData.Paper,System.Int32]

如何在文本文件中打印所有这些值?

您需要计算返回的 IEnumerable:

eAuthor.Papers.Select(p => p.PaperID)

字符串格式化程序将在 IEnumerable 上调用 ToString,这就是您得到的原因:

System.Linq.Enumerable+WhereSelectListIterator`2[DirichletProcessClustering.GraphData.Paper,System.Int32]

您可以添加一个额外的 foreach 语句并枚举上面的 IEnumerable 来为作者编写论文 ID 和年份,如下所示:

foreach (EvoObject eEvoObject in curCluster.GetClusterObjects())
{
      Author eAuthor = (Author)eEvoObject.GetOriginalObject();

      twObjClus.WriteLine(
          @"AuthorID: {0}, AuthorName: {1} \n",
           eAuthor.AuthorID,
           eAuthor.AuthorName);

       foreach (var paper in eAuthor.Papers)
       {
           twObjClus.WriteLine(
             @"PaperID: {0}, Year: {1}", paper.PaperID, paper.Year);
       }
}