Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ where condition filtering

Tags:

c#

linq

String Sex = getSex(); // return M or F
String[] members = getMembers(); // return member codes in array or null
//if members array is null, no filtering for member codes
var query = from tb in MemberTable
            where tb.sex.Equals(Sex) && 
                  (members != null ? members.Contains(tb.membercode) : true)
            select tb;

The code doesn't return correct result. It returns all members no matter what members[] is.

Actually the original LINQ is complex so if there are any other possible solutions, I do not want to write the following:

if (members == null){ /*LINQ1*/ }
else { /*LINQ2*/ }

which is not a good coding style. Any suggestion for solving this problem?

like image 771
Pang Avatar asked Dec 04 '13 03:12

Pang


People also ask

How to use where clause in LINQ query in C#?

Where Clause in Query Syntax: The where clause is used to filter the query according to the given condition. You can provide a condition to where clause using lambda expression or by using Func delegate type. Where clause supports query syntax in both C# and VB.Net languages.

Which clause is used for conditions in Linq?

In LINQ, we can use Where() clause in the query to define multiple conditions, as shown below. This is how we can use LINQ where clause filtering operator to filter data based on conditions.

Which Linq operator is used to define a condition to filter data from any given DataSet?

The Where operator (Linq extension method) filters the collection based on a given criteria expression and returns a new collection. The criteria can be specified as lambda expression or Func delegate type.

Where clause C#?

The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true.


2 Answers

var query = MemberTable.Where(x=>x.sex.Equals(Sex))

if (members != null)
     query = query.Where(x=>members.Contains(x.membercode))

//use your query
query.ToList();

OR

var query = from tb in MemberTable
        where tb.sex.Equals(Sex) && 
              (members == null || members.Contains(tb.membercode))
        select tb;

I prefer the first.

like image 138
Alexey Raga Avatar answered Sep 21 '22 05:09

Alexey Raga


Since || short-circuits, you should be able to do this:

var query = from tb in MemberTable
    where tb.sex.Equals(Sex) && 
          (members == null || members.Contains(tb.membercode))
    select tb;

The (members == null || members.Contains(tb.membercode)) subexpression will be true if members is null, so Contains would not be evaluated.

like image 20
Sergey Kalinichenko Avatar answered Sep 19 '22 05:09

Sergey Kalinichenko