2014-09-05 146 views
0

好了,我試圖把這個:可能在聲明中使用匿名類型成員嗎?

sSelect = "SELECT CONVERT(VARCHAR, CommitDate, 101) AS XLabel, " + 
    "SUM(CASE WHEN NOT CompletionDate IS NULL THEN 1 ELSE 0 END) AS ClosedEvents, " + 
    "COUNT(CommitDate) AS Total, " + 
    "COUNT(CommitDate) - SUM(CASE WHEN NOT CompletionDate IS NULL THEN 1 ELSE 0 END) AS OpenEvents, " + 
    "SUM(CASE WHEN CompletionDate IS NULL AND commitdate < Convert(varchar(12),getdate(),101) THEN 1 ELSE 0 END) AS BehindSchedule"; 

到LINQ查詢。到目前爲止,我得到了:

var vEventsEntriesEnum = dtEventsEntries.AsEnumerable(); 

var vOpenEntriesData = from r in vEventsEntriesEnum 
select new 
{ 
    XLabel = r["CommitDate"], 
    ClosedEvents = vEventsEntriesEnum.Sum(closed => (closed["CompletionDate"] != null) ? 1 : 0), 
    Total = vEventsEntriesEnum.Count(total => (total["CommitDate"] != null) ? true : false), 
    OpenEvents = Total - ClosedEvents, 
}; 

這是我意識到我可能有問題。在這種情況下,Total和ClosedEvents不存在。

雖然我可以繼續前進,重複查詢ClosedEvents和Total和cast然後減去它們或任何東西,但我希望會有更好的方法。

如果還有其他的方式來處理我正在處理的其他代碼,請隨時通知我。

任何想法?

+0

如果您創建的是實際的類而不是匿名類型,那麼您的屬性'OpenEvents'可以返回'Total - ClosedEvents' – 2014-09-05 15:26:56

+0

從長遠來看,這可能更容易。謝謝! – Aphrodisizach 2014-09-05 15:30:44

回答

0

你必須在某個地方實現它。在查詢語法中,您可以使用以下代碼:let clause

var vOpenEntriesData = from r in vEventsEntriesEnum 
    let ClosedEvents = vEventsEntriesEnum.Sum(closed => (closed["CompletionDate"] != null) ? 1 : 0) 
    select new 
    { 
     XLabel = r["CommitDate"], 
     ClosedEvents, 
     Total = vEventsEntriesEnum.Count(total => (total["CommitDate"] != null) ? true : false), 
     OpenEvents = Total - ClosedEvents, 
    }; 

這與循環中的變量類似。

相關問題