簡體   English   中英

如何返回IEnumerable?

[英]How do I return an IEnumerable?

我正在嘗試返回IEnumerable。 這是我的代碼:

public static IEnumerable<int> GetAnswersIDs(int id)
{
    using (var context = new MvcApplication4.Entity.test2Entities1())
    {
        return (from p in context.post
                  where p.post_parentid == id && p.post_isdeleted == false
                  select new
                  {
                      p.post_id
                  }).ToList();
    }           
}

是否可以返回IEnumerable對象?

您不需要使用任何To [Anything]方法或類似方法。 您的錯誤是您的選擇方式。 正確的代碼是這樣的:

public static IEnumerable<int> GetAnswersIDs(int id)
{
    using (var context = new MvcApplication4.Entity.test2Entities1())
    {
        return (from p in context.post
                  where p.post_parentid == id && p.post_isdeleted == false
                  select p.post_id);
    }           
}

如您所見,您創建了一個不需要的匿名類,因為您只需要一個int值。

-編輯-

您將面臨ObjectDisposed異常。 例如,當您使用返回的IEnumerable對象時,需要使用GetAnswersIDs方法中放置的上下文。

因此,您可以返回一個List而不是IEnumerable,或者應該從GetAnswersIDs方法中定義上下文。

這是清單的代碼

public static List<int> GetAnswersIDs(int id)
{
    using (var context = new MvcApplication4.Entity.test2Entities1())
    {
        return (from p in context.post
                  where p.post_parentid == id && p.post_isdeleted == false
                  select p.post_id).ToList();
    }           
}

我認為您應該使用ToArrayToListArray<T>List<T>實現IEnumerable<T> ),因為當您返回上下文時,我幾乎可以肯定,如果使用AsEnumerable離開,您將獲得異常枚舉本身,以用於后續步驟:

public static IEnumerable<int> GetAnswersIDs(int id)
{
    using (var context = new MvcApplication4.Entity.test2Entities1())
    {
        return (from p in context.post
                  where p.post_parentid == id && p.post_isdeleted == false
                  select p.post_id).ToArray();
    }           
}

順便說一句,我認為在您的情況下,使用linq比使用非linq版本更為冗長:

public static IEnumerable<int> GetAnswersIDs(int id)
{
    using (var context = new MvcApplication4.Entity.test2Entities1())
    {
        return context.post.
          Where(p => p.post_parentid == id && !p.post_isdeleted).
          Select(p => p.post_id).
          ToArray();
    }           
}

附帶說明一下,您可能需要考慮重新格式化模型中的字段名稱,以滿足.NET中命名約定

我認為您正在尋找AsEnumerable()

但是,在查看代碼之后,您必須完全實現查詢的結果,因此使用ToList()是合適的-否則,當您稍后嘗試枚舉結果時,您將獲得異常,因為它將嘗試訪問已處置的數據庫數據庫上下文。

我認為您不需要select new {}
select p.post_id應該足夠了! 然后,您可以使用.AsEnumerable()其包圍

對於基本IEnumerable收益,使用yield收益

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM