LINQ条件和

时间:2017-09-13 08:50:53

标签: c# linq

我有一组带过滤器的数组,需要匹配为"和"操作。我的过滤器数组是空的,它应该是interpreeted包含此过滤器的所有内容:

List<string> cars = new List<string>();
List<string> flights = new List<string>();
            flights.Add("Boing");
            flights.Add("Airbus");

            var transports = new List<Transport>();
            var t1 = new Transport("Ford", "Boing");
            var t2 = new Transport("BMW", "Boing");
            var t3 = new Transport("BMW", "Flights INC");

            transports.Add(t1);
            transports.Add(t2);
            transports.Add(t3);

            //returns 0 result. In this scenario I would expect to get all with boing and Airbus and cars excluded from search because its empty
            var result = transports.Where(p => 
                (cars.Count>0 && cars.Contains(p.CarType)) && 
                (flights.Count > 0 && flights.Contains(p.FlightType))).ToList();


        cars = new List<string>();
            flights = new List<string>();
            cars.Add("BMW");
            flights.Add("Boing");

            IEnumerable<Transport> result2 = transports;

            if (cars?.Any() == true)
            {
                result2 = transports.Where(p => cars.Contains(p.CarType));
            }
            if (flights?.Any() == true)
            {
                result2 = transports.Where(p => flights.Contains(p.FlightType));
            }

            // all rows returned here I only want t2
            var r = result2.ToList();

拉胡尔指导方向正确。数组不能为null。解决它:

                     statusViewResult = statusViewResult.Where(p=> 
            (query.ClustersSelected.Count == 0 || query.ClustersSelected.Contains(p.Cluster)) && 
            (query.ParkNamesSelected.Count == 0 || query.ParkNamesSelected.Contains(p.ParkName)));

2 个答案:

答案 0 :(得分:2)

一个简单的if会这样做:

if(query.ClustersSelected?.Any() == true)
{
    statusViewResult = statusViewResult.Where(p => query.ClustersSelected.Contains(p.Cluster));
}
if(query.ParkNamesSelected?.Any() == true)
{
    statusViewResult = statusViewResult.Where(p => query.ParkNamesSelected.Contains(p.ParkName));
}

每个考虑因素都会为集合添加另一个过滤器。我经常将这些代码与Entity Framework(和IQueryable)一起使用来生成较小的SQL查询,但它对于LINQ to objects(IEnumerable)也同样有用。
我正在使用ClustersSelected?.Any() == true来捕获null属性和空集合的两种情况。

答案 1 :(得分:1)

你可以使用下面的复合条件,考虑ClustersSelected是数组类型

.Where(p => query.ClustersSelected.Length > 0 &&  query.ClustersSelected.Contains(p.Cluster)