我的代码中定义的Dictionary
为:
public Dictionary<int, Tuple<List<int>, int, int, int>> GetAuthorData(int startYear, int endYear)
{
Dictionary<int, Tuple<List<int>>, int, int, int>> authorData;
foreach (var paper in Papers.Where(p => p.Year >= startYear && p.Year <= endYear))
{
authorData.Add(paper.PaperID,
new Tuple<List<int>, int, int, int>(
paper.CoAuthors, paper.PaperCategory, paper.VenueID, paper.Year)
);
}
return authorData;
}
问题在于添加paper.CoAuthors
,因为它是List<int>
,因此它不能正确填充列表中的列表。
更新
列表Papers
定义为:
public List<Paper> Papers { get; set; }
而类Paper.cs
定义为:
public class Paper
{
// Class constructor
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; }
}
使用GetAuthorData()
:
Dictionary<int, Author.AuthorData> tauthorData = eAuthor.GetAuthorData(year, year + 1);
foreach( var kvauthor in tauthorData)
{
tw.WriteLine("PaperID: {0}, CoAuthors: {1}, PaperCategory: {2}, Venue: {3}, Year: {4}",
kvauthor.Key, kvauthor.Value.CoAuthors, kvauthor.Value.PaperCategory,
kvauthor.Value.VenueID, kvauthor.Value.Year);
}
所需输出
PaperID: 1, CoAuthorID: 23, PaperCategory: 6, VenueID: 3454, Year: 2016
PaperID: 1, CoAuthorID: 24, PaperCategory: 6, VenueID: 3454, Year: 2016
PaperID: 1, CoAuthorID: 25, PaperCategory: 6, VenueID: 3454, Year: 2016
PaperID: 1, CoAuthorID: 26, PaperCategory: 6, VenueID: 3454, Year: 2016
PaperID: 2, CoAuthorID: 27, PaperCategory: 7, VenueID: 3455, Year: 2016
PaperID: 2, CoAuthorID: 28, PaperCategory: 7, VenueID: 3455, Year: 2016
PaperID: 2, CoAuthorID: 29, PaperCategory: 7, VenueID: 3455, Year: 2016
我们如何才能正确添加CoAuthors
列表?
答案 0 :(得分:1)
您需要初始化字典:
public Dictionary<int, AuthorData> GetAuthorData(int startYear, int endYear)
{
var authorData = new Dictionary<int, AuthorData>();
foreach (var paper in Papers.Where(p => p.Year >= startYear && p.Year <= endYear))
{
Console.WriteLine(paper.CoAuthors.Count.ToString());
authorData.Add(paper.PaperID,
new AuthorData()
{
CoAuthors = paper.CoAuthors,
PaperCategory = paper.PaperCategory,
VenueID = paper.VenueID,
Year = paper.Year
});
Console.WriteLine("After");
Console.WriteLine(authorData.Last().Value.Count.ToString());
}
return authorData;
}
class AuthorData
{
public List<int> CoAuthors { set; get; }
public int PaperCategory { set; get; }
public int VenueID { set; get; }
public int Year { set; get; }
}
至于您的打印代码,您需要这样做:
Dictionary<int, Author.AuthorData> tauthorData = eAuthor.GetAuthorData(year, year + 1);
foreach (var kvauthor in tauthorData)
{
foreach (var author in kvauthor.Value.CoAuthors)
{
tw.WriteLine("PaperID: {0}, CoAuthors: {1}, PaperCategory: {2}, Venue: {3}, Year: {4}",
kvauthor.Key, author, kvauthor.Value.PaperCategory,
kvauthor.Value.VenueID, kvauthor.Value.Year);
}
}