Linq NOT IN查询 - 基于SQL查询

时间:2016-08-01 20:43:07

标签: c# linq

我正在试图弄清楚如何将这个相同的SQL查询转换为Linq查询,但是我没有看到像使用SQL那样使用Linq进行NOT IN的方法。

SELECT COUNT(DISTINCT ID) 
FROM References 
WHERE ID NOT IN (
    SELECT DISTINCT ID 
    FROM References
    WHERE STATUS = 'COMPLETED')
AND STATUS = 'FAILED'

我需要知道有多少个不同的[ID]值包含[Status]值为“FAILED”且不具有[Status]“COMPLETED”的[Status]值。基本上,如果没有完成失败,我需要不同的金额。

var query_5 = from r in Records where r.ID NOT IN(from r in Records where
r.Record_Status == "COMPLETED" ) && (r.Record_Status == "FAILED") 
select r.ID;

var rec_5 = query_5;
Console.WriteLine(rec_5.Distinct());

这是我尝试这样做的,但我收到了很多错误,因为它不是编码它的正确方法。任何关于如何实现这一目标的例子都将非常感激!

这就是我的其他设置的外观。

public class References
{
  public string ID;
  public string Record_Status;
}

public static List<References> Records = new List<References>
{
};

2 个答案:

答案 0 :(得分:1)

(not) in的粗略等效词正在使用Contains()。由于内部子查询没有引用外部,你可以这样写:

var completedIds =
    (from r in ctx.References
    where r.Status == "COMPLETED"
    select r.Id).Distinct();

var count =
    (from r in ctx.References
    where !completedIds.Contains(r.ID)
    where r.Status == "FAILED"
    select r.Id).Distinct().Count();

答案 1 :(得分:0)

您可以使用Except方法:

var completed =
    (from r in References
        where r.Record_Status == "COMPLETED"
        select r.Id).Distinct();

var failed =
    (from r in References
        where r.Record_Status == "FAILED"
        select r.Id).Distinct();

var countFailedNotCompleted = failed.Except(completed).Count();

请注意,这不需要在迭代期间使用Contains。序列将在Except方法中一次性进行比较。您还可以将ToArray()添加到每个不同的序列上,以确保在您想要多次使用这些序列的情况下进行最小的迭代。

相关问题