简体   繁体   中英

Operator '??' cannot be applied to operands of type 'System.Guid?' and 'string'

I am getting this error in a LINQ query with the below code:

"Operator '??' cannot be applied to operands of type 'System.Guid?' and 'string'"

I have a nullable GUID object , here I am checking if the GUID Object is null , then I need to return String.Empty else will be converting GUID to string

List<Report> queryresult =
    reportDatatable.AsEnumerable()
        .Where(c => c.Field<Guid?>("ParentID") == Guid.Parse("XXXXXX-XXX-XXXXX-XXXXX-XXX))
        .Select(c=> new Report()
        {
            ID = (c.Field<Guid?>("ID") ?? String.Empty).ToString(), //error here
            ...
        }).ToList();

Below link as simplest way to check whether object is null or not.

Suggest if any other approach to check GUID object is null or not

Edit:

Apparently, what suits your need best would be this:

ID = (c.Field<Guid?>("ID") ?? Guid.Empty) == Guid.Empty ? String.Empty : c.Field<Guid?>("ID").ToString(), //try this

Original

Convert your GUID to string first:

c.Field<Guid?>("ID").ToString() ?? String.Empty

Then it should be ok.

Else, use Guid.Empty instead of String.Empty the idea here is that both sides in ?? must match. Like comparing Apple to Apple

To prevent c.Field<Guid?>("ID") == null being executed, in C#6, you could make it more simply like this

c.Field<Guid?>("ID")?.ToString() ?? String.Empty

Given that Nullable<> 's ToString() override produces an empty string if the value is null, you can simply write

ID = c.Field<Guid?>("ID").ToString()

Depending on your reporting code, better yet could be to make Report 's ID of type Guid? , but that won't necessarily always work.

You need to return Guid.Empty instead of String.Empty for ?? operator as left hand side is Guid not string . That is what the compiler error "Operator '??' cannot be applied to operands of type 'System.Guid?' and 'string'" suggests.

 ID = (c.Field<Guid?>("ID") ?? Guid.Empty).ToString(),

Edit

If you want empty string then you can put condition to return empty string for Guid.Empty. Your query will end up with something like this.

ID = (c.Field<Guid?>("ID") ?? Guid.Empty) == Guid.Empty ? 
        String.Empty : c.Field<Guid?>("ID").ToString(),

由于具有可为空的GUID,因此可以使用HasValue检查值是否存在

(c.Field<Guid?>("ID").HasValue ? c.Field<Guid?>("ID").Value:String.Empty).ToString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM