开发者

Linq where clause tied to dropdownlist selectedvalue

开发者 https://www.devze.com 2023-03-13 02:18 出处:网络
I have a dropDownList1 with 3 values: N, U, All. I have dropDownList2 that is populated by a Linq statement with values filtered by the selection made in the first drop down during the SelectedIndexCh

I have a dropDownList1 with 3 values: N, U, All. I have dropDownList2 that is populated by a Linq statement with values filtered by the selection made in the first drop down during the SelectedIndexChanged event.

开发者_StackOverflow社区string theType = dropDownList1.SelectedValue;

var yearQuery = (from y in context
where y.Type == theType
orderby y.Year ascending
select y.Year).Distinct();

But, the option "All" in the first list is not one of the values in the Type column of the data set. I'd like it when someone selects "All" in the dropdown, it would return all of the records. Is there an equivalent of a * operator? Any ideas?


Try this:

string theType = dropDownList1.SelectedValue;

var yearQuery = (from y in context                    
                orderby y.Year ascending
                select y.Year).Distinct();

if(theType != "All")
    yearQuery = yearQuery.Where(p=>p.Type == theType);


the easiest way to get this started is branch the code and then set yearQuery where there is no type filter when the person selects "all". You can refactor to a more concise option later.


var yearQuery = (from y in context where (y.Type == theType or theType == "ALL") orderby y.Year ascending select y.Year).Distinct();


string theType = dropDownList1.SelectedValue;

var yearQuery = (from y in context
where theType == "All" || y.Type == theType
orderby y.Year ascending
select y.Year).Distinct();

That should work too.

0

精彩评论

暂无评论...
验证码 换一张
取 消