LINQ查询与sub where子句

时间:2013-02-25 14:37:06

标签: c# linq

我有一个SQL查询:

 SELECT [Paypoint]
      ,[Department]
      ,[EmployeeCode]
      ,[Gender]
      ,[EmployeeTitle]
      ,[Initials]
      ,[Surname]
      ,[ItemsIssuedDate]
      ,[ItemsIssuedStockNumber]
  FROM [MyTable] AS a
  WHERE
 (
      [ItemsIssuedDate] =   (   SELECT     max([ItemsIssuedDate])
                                FROM        [MyTable] AS b
                                WHERE       a.[Paypoint] = b.[Paypoint]
                                            AND a.[Department] = b.[Department]
                                            AND a.[EmployeeCode] = b.[EmployeeCode]
                                            AND a.[Gender] = b.[Gender]
                                            AND a.[Surname] = b.[Surname]
                             )

如何获得比较LINQ查询?我无法使用SQL查询,因为数据已经存在于DataSet中,现在需要进一步修改...

我尝试过,但这不起作用:

        var query = from a in excelTable
                    where
                    (
                        from c in excelTable
                        group c by new
                        {
                            c.Paypoint,
                            c.EmployeeCode
                        } into g
                        where string.Compare(a.Paypoint, g.Key.Paypoint) == 0 && string.Compare(a.EmployeeCode, g.Key.Paypoint) == 0
                        select g.Key.Paypoint
                    )
                    select a;

2 个答案:

答案 0 :(得分:2)

var query = from a in MyTable
            group a by new { 
              a.Paypoint,
              a.Department,
              a.EmployeeCode,
              a.Gender, 
              a.Surname
            } into g
            select g.OrderByDescending(x => x.ItemsIssuedDate)
                  //.Select(x => new { required properties })
                    .First();      

您也可以选择仅包含必填字段的匿名对象。由你决定。

答案 1 :(得分:0)

您最直接的SQL查询将是:

var query = 
    from a in excelTable
    let maxIssueDate = 
        (from b in excelTable
         where a.Paypoint == b.Paypoint &&
             a.Department == b.Department &&
             a.EmployeeCode == b.EmployeeCode &&
             a.Gender == b.Gender &&
             a.Surname == b.Surname
         select b.ItemsIssueDate).Max()
    where a.ItemsIssueDate == maxIssueDate
    select a;