简体   繁体   English

LINQ 使用方法语法查询

[英]LINQ Query with method syntax

My requirement is to make boolean value (IsPC=true) only if I found any value with IsCurrent = true from the list and second condition is to filter the list with G or W codes and third condition is to check the PCBNumber length ==15 with only one from the list.我的要求是仅当我从列表中找到 IsCurrent = true 的任何值时才使 boolean 值(IsPC=true),第二个条件是使用 G 或 W 代码过滤列表,第三个条件是检查 PCBNumber 长度 ==15列表中只有一个。

How short can i able to reduce the below query using LINQ method syntax below is my query我能用下面的 LINQ 方法语法减少下面的查询有多短是我的查询

     var CurrentQ= p.List.Where(x => x.IsConCurrent== true);
            if (CurrentQ.Count() > 0)
            {
                var NCurrentQwithWorQ = p.List.Where(x => x.Codes == Codes.W|| x.Codes== Codes.Q).Count();
                if (NCurrentQwithWorQ  != null)
                {
                    var PCBNumber = p.List.Where(x => x.PCBNumber .Length == 15).Count();
                    if (PCBNumber == 1)
                    {
                        isPC = true;
                    }
                }
}

You can use all conditions in same query like below,您可以在同一查询中使用所有条件,如下所示,

var PCBNumber= p.List.Where(x => x.IsConCurrent== true && (x.Codes == Codes.W|| x.Codes== Codes.Q) && x.PCBNumber.Length == 15);
if (PCBNumber !=null && PCBNumber.Count() == 1)
{
   isPC = true;
}

I'm not trying to debug what you wrote, but isn't this really what you're looking for--that is, daisy-chaining your Where conditions?我不是要调试你写的东西,但这不是你真正想要的——也就是说,菊花链你的 Where 条件?

var isPC = p.List.Where(x => x.IsConCurrent == true).Where(x => x.Codes == Codes.W || x.Codes == Codes.Q).Where(x => x.PCBNumber.Length == 15).Count() == 1;

Both solutions suggested above are correct.上面建议的两种解决方案都是正确的。

p.List.Where(x => x.IsConCurrent== true && (x.Codes == Codes.W|| x.Codes== Codes.Q) && x.PCBNumber.Length == 15);
p.List.Where(x => x.IsConCurrent == true).Where(x => x.Codes == Codes.W || x.Codes == Codes.Q).Where(x => x.PCBNumber.Length == 15).Count()

Actually they are performed in the same way.实际上,它们的执行方式相同。 The Where function does not force immediate iteration through the data source. Where function 不强制通过数据源立即迭代。 Only when you execute the Count function, LINQ will process row by row and execute criterion by criterion to find out which values should be calculated.只有当您执行 Count function, LINQ 时,才会逐行处理并逐条执行条件以找出应该计算哪些值。

I can only suggest you add the Take(2) operator after the where clause.我只能建议您在 where 子句之后添加 Take(2) 运算符。 In this case LINQ will stop after finding the first two rows that matches provided criterion and other rows will not be processed.在这种情况下,LINQ 将在找到与提供的标准匹配的前两行后停止,其他行将不被处理。

p.List.Where(x => x.IsConCurrent == true)
   .Where(x => x.Codes == Codes.W || x.Codes == Codes.Q)
   .Where(x => x.PCBNumber.Length == 15)
   .Take(2).Count()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM