2015-07-22 54 views
0

如何在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(); 
    } 
} 

回答

0

你應該考慮拋出異常。 而不是返回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 
} 
+1

這是一個裁判不是一個出來。 –

+0

已更正。 thx爲暗示 – Chaka

+0

對不起,它不工作。實際上我想要給手機留言。這是用於移動應用程序。 –