2013-04-11 24 views
1

我是非常新的LINQ,我在這裏有一個問題。如何在LINQ中使用可空的內置變量?

我有這個非常簡單的類這裏演示的目的:

public class CurrencyPair 
{ 
    public string? cultureCode; 
    public string? currencyName; 

    public CurrencyPair(string iCultureCode, string iCurrencyName) 
    { 
     cultureCode = iCultureCode; 
     currencyName = iCurrencyName; 
    } 

    public CurrencyPair() 
    { 
     cultureCode = ""; 
     currencyName = ""; 
    } 
} 

然後,我有上述類實例的列表:

static List<CurrencyPair> currencyPairs; 

現在我試圖做到這一點:

public List<string> GetCurrencyNames() 
{ 
    return (from c in currencyPairs select c.currencyName).Distinct().ToList(); 
} 

但是我得到這個錯誤:

The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>' 

如果我在類定義中刪除了和currencyName?,則此錯誤消失。

那麼如何在LINQ查詢中使用可空字符串?

回答

8

string已經是一個引用類型,它可以容納null,你不必使用string?

的誤差,表明還有:

The type 'string' must be a non-nullable value type....

您只能使用Nullable<T>與價值類型。

Nullable<T>

Represents a value type that can be assigned null.

您正在嘗試宣告場string?等於Nullable<string>,但這隻能value types來完成。

In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null

+1

是的,對不起,這是我的錯誤。我想我忘記'字符串'實際上確實支持'null'值。不管怎麼說,多謝拉。 – Ahmad 2013-04-12 09:53:31

相關問題