【问题标题】:List<Guid> with LINQ使用 LINQ 列出 <Guid>
【发布时间】:2016-11-02 12:40:46
【问题描述】:

我有一个返回 Guid 列表的方法。我想要以下 linq 查询:

var results = (from t in CurrentDataSource.Table1
               where t.Manager == userId && t.Profile != null
               select t.Profile).ToList();

为什么会出现以下错误:

Error   4   Cannot implicitly convert type 'System.Collections.Generic.List<System.Guid?>' to 'System.Collections.Generic.List<System.Guid>'    

【问题讨论】:

  • 你确定它是从那条线上抛出的吗?看起来不像。
  • 该错误告诉您您正在尝试将List&lt;Guid?&gt; 转换为List&lt;Guid&gt;,这不能隐式完成。不过,我看不出这行代码是如何导致该错误的。
  • 只需选择t.Profile.Value 即可获得Guid 而不是Guid?,因为您已经过滤掉了null
  • 发布编译错误所在的行。此代码不会抛出该错误。

标签: c# linq


【解决方案1】:

您正在检查 t.Profile 是否为 null,并且只返回有效的 Guid,因此显式转换应该有效:

var results = (from t in CurrentDataSource.Table1
           where t.Manager == userId && t.Profile != null
           select (Guid)t.Profile).ToList();

【讨论】:

    【解决方案2】:

    因为您无法将List&lt;Guid?&gt; 转换/转换为List&lt;Guid&gt;。您可以使用:

    var results = (from t in CurrentDataSource.Table1
                   where t.Manager == userId && t.Profile != null
                   select t.Profile.GetValueOrDefault()).ToList();
    

    【讨论】:

    • 不应该ToList() 返回List&lt;Guid?&gt; 而不导致编译错误?此代码不显示列表之间的任何转换,除非 t.ManageruserId 是 GUID 列表
    • @PanagiotisKanavos:当然,显示的代码可以编译。但是 OP 对这个List&lt;Guid?&gt; 做了一些事情,例如将其作为List&lt;Guid&gt; 返回或将其分配给该类型的变量。该代码将无法编译。
    • 虽然 IQuerable 失败:LINQ to Entities 无法识别方法“System.Guid GetValueOrDefault()”方法,并且此方法无法转换为存储表达式。然而,明确的演员表是有效的。
    猜你喜欢
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 2023-03-20
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多