How can I filter a DataSource before applying it to a ListView
I have an Entity datasource, which I need to filter before passing it to the ListView. Here is the unfiltered version (works great):
DataContext db = new DataContext();
ListView1.DataSource = db.Cars;
ListView1.DataBind();
I'm trying to understand how to select only the Cars that are blue (a field/property/row in the database), and pass just those Cars to the ListView. I've been trying variations on this:
String selectedColor = "blue";
DataContext db = new DataContext();
ListView1.DataSource = db.Cars.Any(m => 开发者_开发问答m.Cars.color == selectedColor);
ListView1.DataBind();
Shouldn't this be more like,
ListView1.DataSource = db.Cars.Where(car => car.Color == selectedColor);
Your db.Cars.Any(m => m.Cars.color == selectedColor)
[Correction: should be m.Color instead of m.Cars.Color if you wanted to use it by the way] statement will return true if in your Cars collection there's at least one car with color value as that of the selectedColor.
Any()
Returns a bool. You need Where()
I would also wrap your context using a using
statement. This should take care of your context's disposal automatically.
String selectedColor = "blue";
using(DataContext db = new DataContext())
{
ListView1.DataSource = db.Cars.Where(m => m.Cars.color == selectedColor);
ListView1.DataBind();
}
精彩评论