2015-12-30 69 views
1

我使用下面的代碼,以年度比較兩個日期:如何比較Linq中日期字段的年份?

public string GetResultWbyYears() 
    { 
     using (var context = new DbEntity()) 
     { 
      int yeat = DateTime.Now.Year; 
      var holidays = (from rl in context.HolidayMasters 
          where rl.Isactive == true && rl.Isdelete == false //&& rl.HolidayDate.Year == yeat 
          orderby rl.HolidayDate ascending 
          select new HolidayEntity 
          { 
           HolidayDesc = rl.HolidayDesc, 
           HolidayDate = rl.HolidayDate, 
           HolidayId = rl.HolidayId 

          }).ToList().AsEnumerable().Select(x => new HolidayEntity() 
      { 
       HolidayDesc = x.HolidayDesc, 
       HolidayDate = x.HolidayDate, 
       Isactive = x.Isactive, 
       Isdelete = x.Isdelete, 
       HolidayId = x.HolidayId, 
       Zones = GetZonesWithSelectedForHolidays(x.HolidayId) 
      }).ToList(); 

      holidays = holidays.Where(n => n.HolidayDate.Year == yeat).ToList(); 
     } 

沒有得到爲什麼上面不工作。請幫助我,我怎樣才能通過一年的結果。

我搜索了谷歌,發現一些文章做了同樣的事情,我做了上面的事情,但這不適合我。這就是爲什麼我發佈了這個問題。

+0

你爲什麼選擇'的IEnumerable ',然後將其轉換成'List',然後選擇'的IEnumerable '一次嗎?你的'Isactive'和'Isdelete'將一直是默認值('false',我猜)。 –

+0

你有什麼錯誤嗎?你的代碼對我來說好像 –

+0

@ kienct89沒有錯誤。但總是返回0條記錄。即使在DB中我們也有當前耳朵的記錄 –

回答

1

您選擇IEnumerable<HolidayEntity>,然後將其轉換爲List,失去IsactiveIsdelete值,因爲他們將默認,然後再次選擇IEnumerable<HolidayEntity>
實際上沒有必要這樣做。

你LINQ可以看起來更漂亮:

public string GetResultWbyYears() 
{ 
    int year = DateTime.Now.Year; 
    using (var context = new DbEntity()) 
    { 
     var result = context.HolidayMasters 
      .Where(hm => hm.Isactive && !hm.Isdelete && hm.HolidayDate.Year == year) 
      .OrderBy(hm => hm.HolidayDate) 
      .ToList(); 

     foreach (var item in result) 
      item.Zones = GetZonesWithSelectedForHolidays(item.HolidayId); 
    } 
} 

或以另一種方式:

public string GetResultWbyYears() 
{ 
    int year = DateTime.Now.Year; 
    using (var context = new DbEntity()) 
    { 
     var result = (from hm in dbSet 
      where hm.Isactive && !hm.Isdelete && hm.HolidayDate.Year == 2015 
      orderby hm.HolidayDate ascending 
      select hm).ToList(); 

     foreach (var item in result) 
      item.Zones = GetZonesWithSelectedForHolidays(item.HolidayId); 
    } 
}  

我假設你context.HolidayMastersDbSet<HolidayEntity類型的,因爲它具有相同名稱的所有屬性。否則,使用一個Select

public string GetResultWbyYears() 
{ 
    int year = DateTime.Now.Year; 
    using (var context = new DbEntity()) 
    { 
     var result = (from hm in dbSet 
      where hm.Isactive && !hm.Isdelete && hm.HolidayDate.Year == 2015 
      orderby hm.HolidayDate ascending 
      select new HolidayEntity { 
       HolidayDesc = x.HolidayDesc, 
       HolidayDate = x.HolidayDate, 
       Isactive = x.Isactive, 
       Isdelete = x.Isdelete, 
       HolidayId = x.HolidayId, 
       Zones = GetZonesWithSelectedForHolidays(x.HolidayId) 
      }).ToList(); 
    } 
}