tags:

views:

19

answers:

1

hi, i have wrote a method that filters output with provided query and return it. when one Where excuted; it return correct output but when more than one Where excuted; output is null and Exception occured with message "Enumeration yielded no results". why? how i can fix it?

public IQueryable<SearchResult> PerformSearch(string query, int skip = 0, int take = 5)
    {
        if (!string.IsNullOrEmpty(query))
        {
            var queryList = query.Split('+').ToList();
            var results = GENERATERESULTS();
            string key;
            foreach (string _q in queryList)
            {
                if (_q.StartsWith("(") && _q.EndsWith(")"))
                {
                    key = _q.Replace("(", "").Replace(")", "");
                    results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCultureIgnoreCase));
                }
                else if (_q.StartsWith("\"") && _q.EndsWith("\""))
                {
                    key = _q.Replace("\"", "").Replace("\"", "");
                    results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCulture));
                }
                else if (_q.StartsWith("-(") && _q.EndsWith(")"))
                {
                    key = _q.Replace("-(", "").Replace(")", "");
                    results = results.Where(q=> !q.Title.Contains(key, StringComparison.CurrentCultureIgnoreCase));
                }
                else
                {
                    key = _q;
                    results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCulture));
                }
            }
            this._Count = results.Count();
            results = results.Skip(skip).Take(take);
            this._EndOn = DateTime.Now;
            this.ExecutionTime();
            return results;
        }
        else return null;
    }

thanks in advance ;)

+1  A: 
        string key; 
        foreach (string _q in queryList) 
        { 

Ah, the expression binds to the key variable. You need a new key variable for each execution of the loop.

        foreach (string _q in queryList) 
        { 
           string key; 
David B
thanks, resolved but why? i'm inserted for each loop new value and in tracing i see that value changed to new value!!! :((
Sadegh
each one of these: "q=>" is an expression. Each expression uses the variable "key" (not the value of variable "key"). As the loop proceeds, key's value is changed. Later when the query is executed, key's only value is the value that was present at loop termination. Thus, all those expressions use a single value, instead of using distinct values.
David B
OK thanks ;))))
Sadegh