List in C# - passing multiple entries as a single object
I have a method (C#)
public void MethodName(List<Order> Order, int ID)
I need to pass this to a main page, in which i know to pass integer value t开发者_开发技巧o ID, am not able to pass multiple items in a single list.
The List order should have two number entries, (ie. Order.number1 and Order.number2)
How should i pass a single list as a parameter to this method containing multiple entries of number1 and 2, so that i can loop thro' and find it.
Thanks.
If I understand this correctly, you have:
class Order
{
public int number1 { get; set; }
public int number2 { get; set; }
...
}
List<Order> orders = new List<Order>
{
{ number1 = 123, number2 = 234 },
{ number1 = 321, number2 = 432 }
};
You want to be able to search orders
to find the one where number1 == ID || number2 == ID
. Assuming there is only one Order with the given ID or you are OK using the first one you find you can do:
public Order FindOrderById(List<Order> orders, int id)
{
foreach (Order order in orders)
{
if (order.number1 == id || order.number2 == id)
{
return order;
}
}
// None found. Return null, throw exception, etc.
return null;
}
...
List<Order> orders = new List<Order> { ... };
Order foundOrder = FindOrderById(orders, 123);
if (foundOrder == null)
{
//Not found
}
else
{
//Found
}
You can also use LINQ to shorten this dramatically. I have included some variations.
List<Order> orders = new List<Order> { ... };
int id = 123;
// Throw exception if exactly one order was not found (none or more than one)
Order foundOrder = orders.Single(o => o.number1 == id || o.number2 == id);
// Return null if exactly one order was not found
Order foundOrder = orders.SingleOrDefault(o => o.number1 == id || o.number2 == id);
// Return all orders that matched
IEnumerable<Order> foundOrders = orders.Where(o => o.number1 == id || o.number2 == id);
You can use a class that implements the IList interface. Such as list.
You could do something like:
List<Order> myOrders = new List<Order>();
Then pass this in to the method.
Where Order is the order object that you are trying to access.
You can return a list from your method (if I'm understanding you correctly)
Edited now that I think I understand better
public void MethodName(List<item> order, int ID) {
foreach(Order O in Order)
{
RunQuery(O.num1, O.num2);
}
}
Without some knowledge of how your database is set up it's tough to write the query code; I leave that to you.
精彩评论