So I'm a bit stuck! Doing a programming assignment for college and I hit a wall.
The question we were given in one of our parts is as follows:
"2. Allow the user to find the customers that have placed an order in a particular year. Provide a combo box which lists all the unique (distinct) years in orders table from which the user can make a selection."
I'm having an issue with converting the "Year" so I can compare it with the OrderID and display all the orders that are in the database, in a listbox.
If anyone could give me a hand it would be greatly appreciated! Thanks!
Here's my code:
private void dateDDL_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selection;
selection = dateDDL.SelectedItem.ToString();
var year = from y in northwind.Orders
where Convert.ToString(y.OrderDate).Contains(selection)
select y.OrderID;
var order = from o in northwind.Order_Details
where o.OrderID == year
select new { o.OrderID,
o.ProductID,
o.UnitPrice,
o.Quantity,
o.Discount };
lbxOrderdate.ItemsSource = order;
}
var year = (from y in northwind.Orders
where Convert.ToString(y.OrderDate).Contains(selection)
select y.OrderID).Single();
var order = from o in northwind.Order_Details
where o.OrderID == year
select new {
o.OrderID,
o.ProductID,
o.UnitPrice,
o.Quantity,
o.Discount
};
LINQ query also returns System.Linq.IQueryable<T>
and, if you want to take single value, you should you Single()
/ First()
extension.
If you not sure, that query result contains objects, you should you FirstOrDefault()
or SingleOrDefault()
( SingleOrDefault()
throws an exception when collection contains mere then one element), which returns default(T)
in case when there is no elements in result. Be aware of this.
Your year
query is returning a list of all the OrderID
values that match your where
clause. You can't compare that list to the single o.OrderID
in the order
query; if you want to find all the orders that are in one of the years returned by the years
query, use something like
where year.Contains(o.OrderID)
(untested, but should lead you down the right route)
Type is very important, the world of (nothing but) strings is not safe.
string selection = dateDDL.SelectedItem.ToString();
int year = Int32.Parse(selection);
var orders =
from order in northwind.Orders
where order.OrderDate.Year == year
select order;
"2. Allow the user to find the customers that have placed an order in a particular year. Provide a combo box which lists all the unique (distinct) years in orders table from which the user can make a selection."
Hmm, shouldn't the query actually be about customers?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.