首页 > 解决方案 > 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.

How short can i able to reduce the below query using LINQ method syntax below is my query

     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;
                    }
                }
}

标签: c#performancelinq

解决方案


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;
}

推荐阅读