我有一些从数据库查询的数据,但如果某个财政年度没有记录,则不会在我的列表中返回。我需要返回所有财务年度,但实际信息(GrossEx,GST,GrossInc)都应该为空。
public class FinancialData
{
public string FinancialYear { get; set; }
public string Type { get; set; }
public decimal? GrossEx { get; set; }
public decimal? GST { get; set; }
public decimal? GrossInc { get; set; }
}
如果不存在,我如何有效地将2004年至2015年(Gross,GST和GrossInc为空)的FinancialYears添加到我的列表中?
List<FinancialData> financialDataBucket = new List<FinancialData>();
FinancialData entry1 = new FinancialData { FinancialYear = "2012 - 2013", GrossEx = 1, GrossInc = 1, GST = 1 };
FinancialData entry2 = new FinancialData { FinancialYear = "2013 - 2014", GrossEx = 1, GrossInc = 1, GST = 1 };
financialDataBucket.Add(entry1);
financialDataBucket.Add(entry2);
我尝试用linq比较器做联盟,但由于某种原因它没有用,我无法弄清楚为什么?这是解决问题的最佳方法吗?
var merged = allFinancialYearsData.Union(financialDataBucket, new EqComparer());
public class EqComparer : IEqualityComparer<FinancialData>
{
public bool Equals( FinancialData x, FinancialData y )
{
return x.FinancialYear == y.FinancialYear;
}
public int GetHashCode( FinancialData obj )
{
return obj.GetHashCode ();
}
}
编辑:
所以,我考虑创建10个不同的财务年度对象并将它们添加到列表中,或者
var currentYear = DateTime.Now.Year + (DateTime.Now.Month < 7 ? 0 : 1);
var earliestYear = 2005;
for (int i = earliestYear; i <= currentYear; i++) {
//Instantiate FinancialData here.....
financialDataItem.FinancialYear = (i-1) + " - " + i
}
谢谢!
答案 0 :(得分:1)
您必须执行群组加入。在下面的代码片段中,allRecords为&#34; 2005 - 2006&#34;创建虚拟财务数据。到&#34; 2014 - 2015&#34;。
var allRecords = Enumerable.Range(0, 10).Select(x => new FinancialData { FinancialYear = string.Format("{0} - {1}", 2005 + x, 2005 + x + 1) });
var myRecords = new[] { new FinancialData { FinancialYear = "2012 - 2013", GrossEx = 1, GrossInc = 1, GST = 1 }, new FinancialData { FinancialYear = "2013 - 2014", GrossEx = 1, GrossInc = 1, GST = 1 } };
var result = allRecords.GroupJoin(myRecords
, x => x.FinancialYear, y => y.FinancialYear, (x, y) => y.FirstOrDefault(u => u.FinancialYear == x.FinancialYear) ?? x);