簡體   English   中英

使用LINQ調用存儲過程,如何從方法中傳回var?

[英]Using LINQ calling a sproc, how can I pass a var back from a method?

我有這種方法工作了一段時間

public string getSlotText(int slotID)
{
    DataClasses1DataContext context = new DataClasses1DataContext();

    var slotString = context.spGetSlotTextBySlotID(slotID);

    return slotString.ElementAt(0).slotText;

}

但是我現在真正想要的是

public var getSlotText(int slotID)
{
    DataClasses1DataContext context = new DataClasses1DataContext();

    var slotString = context.spGetSlotTextBySlotID(slotID);

    return slotString;
}

因為slotString中包含多個元素。 我看到了其他一些示例,但是沒有一個LINQ調用了sproc。

任何幫助都將是驚人的,id非常感謝。

非常感謝

提姆

不允許將var關鍵字作為返回類型。 它只能在帶有初始化的方法和類成員中使用。

盡管有可能對返回類型進行類型推斷,這可能會違反C#中的其他功能。 例如匿名類型。 由於方法無法在C#中返回匿名類型,因此您需要進行另一項檢查,以確保您不能返回匿名類型,而不僅僅是禁止var關鍵字作為返回類型。

此外,允許var作為返回類型會使更改實現時方法簽名不穩定。

編輯:尚不清楚您希望返回什么,但是這里有一些標准的解決方案:

如果要從結果返回所有slotText

return context.spGetSlotTextBySlotID(slotID).Select(s=> s.slotText).ToList());

(將返回List<string>

或者,如果您想返回所有SlotText (或從SlotText返回的任何類型)

return context.spGetSlotTextBySlotID(slotID).Select(s=> s.slotText).ToList());

(將返回List<SlotText>

暫無
暫無

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

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