0

Consider i have the following linq query.I want to specify the condition in where clause as a string as i will make it empty when i wont have any condition.But on doing so i am getting the error : "Cant explitily convert string to bool".I know the reason for the error.I just want to know is there any other alternative to implement the following.

var elements = from element in array
               orderby element descending
               where element > 2
               select element;

string condition="element >"+2;

I want to do the following....

var elements = from element in array
               orderby element descending
               where condition<------------            
                           select element;

PS:I will handle the situation when there is no condition and the where clause is left with no condition.

Thanks in advance...

1

2 Answers 2

1

Query syntax is translated into normal syntax by the compiler, so your example is equivalent to:

var elements = array.OrderByDescending(element => element).Where(element => element > 2);

Both OrderByDescending and Where return an IEnumerable<T>. What Where does is inserting a Func<T, bool> as a filter, so when you iterate over the enumerable, it calls that function for each element and skips the element if the function returns false. If you don't have a condition, you can simply leave out the call to Where:

var elements = array.OrderByDescending(element => element);

If, later, you need to select only certain elements, you can apply your filter to elements:

elements = elements.Where(element => element > 2);

If your filter depends on user input, you can use closures (functions that capture external variables):

public Func<int, bool> CreateFilter(int value)
{
    // This returns a function that 'remembers' the given value:
    return element => element > value;
}

Which can then be used like:

int userInput = 5;
elements = array.OrderByDescending(element => element).Where(CreateFilter(userInput));
Sign up to request clarification or add additional context in comments.

Comments

1

You can split this condition into two like

   var elements = array.OrderByDescending(o => o);
   if (put some condition for active where )
         elements= elements.Where(o=>o>2); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.