我有以下数据项:
Dictionary<int, Tuple<int, int>> tPapers = eAuthor.GetPapersBetweenYears(year, year + 1);
List<int> tCoAuthors = eAuthor.GetCoAuthorsBetweenYears(year, year + 1);
List<int> tVenues = eAuthor.GetVenuesBetweenYears(year, year + 1);
我必须将所有这些数据项(即
tPapers
,tCoAuthors
和tVenues
)写入文本文件。我尝试为:foreach (var kvpaper in tPapers)
{
// Key is Paper_ID, Item1 is Paper_Category, Item2 is Year
twObjClus.WriteLine("PaperID: {0}, PaperCategory: {1}, Year: {2}",
kvpaper.Key, kvpaper.Value.Item1, kvpaper.Value.Item2);
}
而我想以这种形式编写输出:
Paper_ID:1,Paper_Category:3,CoAutohr_ID:34,Venue_ID:23,Year:
2005年
如何在单个
foreach()
循环或每个数据项所需的单独循环中使用所有这些数据项? 最佳答案
您目前没有解决问题的工具。您的方法GetCoAuthorsBetweenYears
和GetVenuesBetweenYears
根本不返回必要的信息。
为什么?那么,您如何将GetCoAuthorsBetweenYears
返回的任何给定记录与Paper_Id
相关联?此方法只返回存储在CoAuthors
中的所有eAuthors
。您需要的是一种具有以下签名之一的方法:
List<Tuple<int, int>> GetDocumentsAndCoAuthorsBetweenYears(int lower, int upper) //Tuple.Value1 stores Paper_Id and Tuple.Value2 stores CoAuthor_ID.
List<int> GetCoAuthorsByDocumentBetweenYears(int documentId, int lower, int upper)
现在,在两种情况下,您都可以将
CoAuthor_ID
信息与Paper_ID
相关联。与场地相同。好的,但是如果您可以修改这些方法,那么为什么我们要从头开始呢?是什么使您无法实现以下一项:
IEnumerable<PaperInfo> GetPaperInfoBetweenYears(int lower, int upper);
PaperInfo
将是:class PaperInfo
{
public int Paper_ID { get; set; }
public int CoAuthor_ID { get; set; }
public int Paper_Category { get; set; }
public int Venue_ID { get; set; }
}
现在,您只需打印
IEnumerable<PaperInfo>
:var papers = GetAllPaperInfoBetweenYears(year, year + 1);
var printedInfo = string.Join(Environment.NewLine,
papers.Select(p => string.Format("{0} {1} {2} {3}", p.Paper_ID, p.Paper_Category, p.CoAuthor_ID, p.Venue_ID));
更新根据您的评论,我整理了一个小例子:
public class Author
{
public int Paper_ID { get; set; }
public int CoAuthor_ID { get; set; }
public int Venue_ID { get; set; }
public int Paper_Category { get; set; }
public int Year { get; }
public int Publisher_ID { get; }
//etc.
}
//bring all info from database
IEnumerable<Author> eAuthors = GetAllInfoFromDB();
//Now filter and project what you need
public static IEnumerable<PaperInfo> GetGetPaperInfoBetweenYears(this List<Author> eAuthors, int lower, int upper)
{
return from eAuthor in eAuthors
where (eAuthor.Year >= lower && eAuthor.Year < upper)
select new PaperInfo() { Paper_ID = eAuthor.Paper_ID, CoAuthor_ID = eAuthor.CoAuthor_ID, Paper_Category = eAuthor.Paper_Category, Venue_ID = eAuthor.Venue_ID };
}
当然,您甚至可以不使用
PaperInfo
而只按年份过滤并投影存储在eAuthorInfo
中的全部信息:public static IEnumerable<PaperInfo> GetGetPaperInfoBetweenYears(this List<Author> eAuthors, int lower, int upper)
{
return from eAuthor in eAuthors
where (eAuthor.Year >= lower && eAuthor.Year < upper)
select eAuthor;
}
并且,与以前一样,只需打印出所需的信息即可:
var printedInfo = string.Join(Environment.NewLine,
papers.Select(p => string.Format("{0} {1} {2} {3}", p.Paper_ID, p.Paper_Category, p.CoAuthor_ID, p.Venue_ID)); //no year, publisher, etc. info
这就是我要做的方式,投射确实有用,但是当您有很多投射并且您不能使用匿名类型时,这会很麻烦。它使您必须为每个投影实现一个类型。