LINQ子查询问题

时间:2014-02-26 08:31:02

标签: linq

以下是我的linq查询:

var varResourceStatusReportDataBase = 
     (
       from content in listContent
       join workflowInstance in listWorkflkowInstance 
         on content.Field<string>("ows_ID").Trim() 
           equals workflowInstance.Field<string>("ows_Content ID").Split(';')[0].Trim()
       join WorkflowInstanceStep in listWorkflowInstanceStep 
         on workflowInstance.Field<string>("ows_ID") 
           equals WorkflowInstanceStep.Field<string>("ows_Workflow Instance ID").Split(';')[0]
       select new
       {
         ContentName = content.Field<string>("ows_Name"),
         WorkflowInstanceId = workflowInstance.Field<string>("ows_ID"),
         WIName = workflowInstance.Field<string>("ows_Title"),
         WIPlannedStartDate = workflowInstance.Field<string>("ows_Planned Start Date") ?? "",
         WIPlannedEndDate = workflowInstance.Field<string>("ows_Planned End Date") ?? "",
         WIActualStartDate = workflowInstance.Field<string>("ows_Actual Start Date") ?? "",
         WIActualEndDate = workflowInstance.Field<string>("ows_Actual End Date") ?? "",
         WIApprovalDate = workflowInstance.Field<string>("ows_Approval Date") ?? "",
         WITaskStatus = workflowInstance.Field<string>("ows_Status").ToUpper() ?? "",
         WIMetadataStatus = workflowInstance.Field<string>("ows_Metadata Status") ?? "",
         WIApprover = workflowInstance.Field<string>("ows_Approver").Replace("#", "").Split(';')[1].ToUpper() ?? "",
         WISResponsible = WorkflowInstanceStep.Field<string>("ows_Responsible").Replace("#", "").Split(';')[1].ToUpper() ?? "",
         WISDesiredEndDate= 
           (
             from WorkflowInstanceStep1 in listWorkflowInstanceStep 
             where (WorkflowInstanceStep1.Field<string>("ows_Status") =="IN PROGRESS" ||
                    WorkflowInstanceStep1.Field<string>("ows_Status") =="ASSIGNED") && 
                    workflowInstance.Field<string>("ows_ID") == WorkflowInstanceStep1.Field<string>("ows_Workflow Instance ID").Split(';')[0]
             select new {abc = WorkflowInstanceStep1.Field<string>("ows_Desired End Date")}).Take(1)
        }).Distinct();

我在上面的查询中有子查询来计算WISDesiredEndDate,但是当我执行此查询时,System.Linq.Enumerable+TakeIterator>d__3a'1[<>f__AnonymousType1'1[System.String]]列的WISDesiredEndDate值不是我想要的实际值。 请给出相同的建议。 感谢。

2 个答案:

答案 0 :(得分:1)

您需要FirstOrDefault()而不是Take(1)

从评论开始,您不需要匿名对象,因此请将选择更改为

select  WorkflowInstanceStep1.Field<string>("ows_Desired End Date")}).FirstOrDefault()

答案 1 :(得分:0)

您可以使用let clause更易读的代码。然而,您必须通过调用FirstOrDefault方法强制执行linq表达式

let desiredEndDate = (from WorkflowInstanceStep1 in listWorkflowInstanceStep .... Take(1))
select new
{
...
     WISDesiredEndDate= desiredEndDate.FirstOrDefault()
}