在声明期间可以使用匿名类型成员吗?

时间:2014-09-05 15:23:33

标签: c# sql linq anonymous-types

好的,所以我试图解决这个问题:

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以及强制转换然后减去它们等等,但我希望有更好的方法。

如果还有其他方法可以执行我正在使用的其余代码,请随时告诉我。

有什么想法吗?

1 个答案:

答案 0 :(得分: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,
    };

这类似于循环中的变量。