回复linq消息
问题描述:
如何在linq中返回消息?请参阅下面的代码。我的返回类型是列表。请帮帮我。回复linq消息
public List<Product> GetProductsByProductName(string storeId, string productName)
{
Authenticate();
int _storeId = Convert.ToInt32(storeId);
string message = "Item is not added to cart";
var _products = (from p in context.products.AsEnumerable()
where p.StoreId == _storeId && p.ProductName.Contains(productName) && p.ProductIsAvailable.Equals(true)
orderby p.ProductName
select
new Product()
{
ProductName = p.ProductName,
CategoryID = p.CategoryId,
QuantityPerUnit = p.ProductUnit,
UnitPrice = p.ProductPrice,
DiscountValue = p.DiscountValue,
DiscountType = p.DiscountType
}).ToList();
if (_products.Count > 0)
{
return _products;
}
else
{
return message.ToList();
}
}
答
你应该考虑抛出异常。 而不是返回meassage.toList尝试:
抛出新的异常(“项目不添加到购物车”);
public List<Product> GetProductsByProductName(string storeId, string productName)
{
...
if (_products.Count > 0)
{
return _products;
}
else
{
throw new Exception("Item is not added to cart");
}
}
你可以处理它,你调用GetProductsByProductName方法
你甚至可以定义自己的异常像ItemAddException之外:异常....
或添加新的出布尔参数告诉你,如果它的工作,或为消息:)
public List<Product> GetProductsByProductName(string storeId, string productName, out string message)
{
...
if (_products.Count > 0)
{
return _products;
}
else
{
message = "Item is not added to cart";
return null; //check if caller can handle nulls ;)
}
}
这样一个不折不扣的字符串参数,如果该方法被称为
var l = GetProductsByProductName(storeId, productName);
你现在会做
string message="";
var l = GetProductsByProductName(string storeId, string productName, out message);
if(String.IsNullOrEmpty(message)==false)
{
.... do stuff
}
,或者如果你使用异常mehtod:
try
{
var l = GetProductsByProductName(storeId, productName);
}
catch(Excepion ex)
{
... do stuff
}
这是一个裁判不是一个出来。 –
已更正。 thx为暗示 – Chaka
对不起,它不工作。实际上我想要给手机留言。这是用于移动应用程序。 –