Linq to work with slightly complex selectlist

Here is a simplified select list

<select name="stuff">
    <option value="">All</option>
    <option>Test</option>
    <option>Test1</option>
    <option>Test2</option>
    <option>Horses</option>
</select>

Based on the value from the select list, I wish to find related values from my table.

LINQ

1. someTable.Where(r => r.someField.Contains(stuff));
2. someTable.Where(r => r.someField == stuff);

3. var a = someTable;
if(stuff != null)
a = a.Where(r => r.someField.Contains(stuff))

The former solution will work properly when the "All" option is selected. Since All is represented by an empty string stuff, .Contains will return true for any case. This breaks when choosing Test, as it will also return Test1 and Test2

The second solution (==) will work fine for all cases except All, and will break if I ever want to use this for a multiple select list.

The third solution will handle All properly, but it will still return Test1 and Test2 if Test is selected.

How can I modify this code to work with All , multiple select, and only selecting exact values?


One way or the other, you would need to add a special case to cover "All" , because it is, well, special. For example, you can rewrite your second solution like this:

someTable.Where(r => string.Empty == stuff || r.someField == stuff);
链接地址: http://www.djcxy.com/p/53744.html

上一篇: 在2个数据表上完全外连接,并有一列列

下一篇: Linq使用稍微复杂的选择列表