如何在LINQ中使用可空的内置变量?

Ahm*_*mad 1 c# 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 = "";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个上面类的实例列表:

static List<CurrencyPair> currencyPairs;
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试这样做:

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

但是我收到此错误:

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>'
Run Code Online (Sandbox Code Playgroud)

如果我删除?for cultureCodecurrencyName类定义,则此错误消失.

那么如何在LINQ查询中使用可空字符串..?

Hab*_*bib 8

string已经是一个引用类型,它可以容纳null,你不必使用string?

错误也表明:

类型'string'必须是不可为空的值类型....

您只能使用Nullable<T>值类型.

Nullable<T>

表示可以指定为null 的值类型.

您正在尝试声明string?等于的字段Nullable<string>,但这只能使用值类型来完成.

在C#和Visual Basic中,使用?将值类型标记为可为空?值类型后的表示法.例如,int?在C#或整数?在Visual Basic中声明一个可以指定为null的整数值类型

.