【问题标题】:Convert session variable list of GUIDs to list of strings将 GUID 的会话变量列表转换为字符串列表
【发布时间】:2017-12-20 16:45:07
【问题描述】:

我有一个设置为 GUID 列表的会话变量。我需要将该 GUID 列表转换为字符串。我对会话变量知之甚少,并且对 C# 的经验有限,因此我尝试了以下可能愚蠢的解决方案:

Session["OtherProgramIDs"] 的类型为 object{System.Collections.Generic.List<System.Guid?>}

不起作用,给我“InvalidCastException”,

无法转换类型的对象 'System.Collections.Generic.List1[System.Nullable1[System.Guid]]' 键入'System.Collections.Generic.List`1[System.String]'":

var otherProgramList = (List<string>)Session["OtherProgramIDs"];

不起作用,这给了我一条消息,说“对象不包含 Select 的定义并且没有扩展方法 Select 接受对象类型的第一个参数”:

var otherProgramList = Session["OtherProgramIDs"].Select(x => (string)x).ToList();

这给了我与上面相同的信息:

var otherProgramList = Session["OtherProgramIDs"].Select(x => x.ToString()).ToList();

我是否需要使用 .ToString() 循环遍历它,然后添加到 otherProgramList 或其他东西?

编辑

我已经添加了上面的错误消息。也尝试过 cmets 的这个建议,并收到上面关于 System.Collections.Generic.List yada yada yada 的相同突出显示的错误。

var otherProgramList = ((IEnumerable&lt;Guid&gt;)Session["OtherProgramIDs"]).Select(x =&gt; x.ToString()).ToList();

仅供参考 - 这个 GUID 可以为空是可以的,还有其他限制因素在起作用。

【问题讨论】:

  • ((IEnumerable&lt;Guid&gt;)Session["OtherProgramIDs"]).Select(x =&gt; x.ToString()).ToList()
  • 定义“不起作用”。你得到了什么例外?
  • 调试的时候Session["OtherProgramIDs]返回的值是什么类型的? (我不是指object - 索引器的返回类型,我是指返回对象的真实类型)。 “不起作用”是什么意思?如果您告诉我们错误消息,我们可以帮助您快 200%。如果您使用x.ToString() 而不是(string)x,我敢打赌您的第二种方法有效。因为GUID 不能强制转换为string,但有ToString() 方法。
  • Guid 不是字符串,因此您不能将其转换为字符串。使用 ToString() 从 GUID 生成字符串。检查文档以获取适用于 Guid.ToString() 的格式说明符
  • 你到底在Session["OtherProgramIDs"]中存储了什么?

标签: c# list


【解决方案1】:

差不多了,首先您需要将 Session 对象映射到 IEnumerable&lt;System.Guid?&gt;,然后在每个 Guid 上使用 .ToString()。

var guids = Session["OtherProgramIDs"] as IEnumerable<System.Guid?>;
if (guids == null) return null;
var otherProgramList = guids.Select(x => x.ToString()).ToList();

如果源列表包含null 的项目,您可能需要添加附加条件。例如。像这样:

var otherProgramList = guids.Where(x => x.HasValue).Select(x => x.ToString()).ToList();

最后但并非最不重要的一点是,IEnumerable&lt;T&gt; 接口被 Linq 大量使用,它允许使用 .Select() 和 .Where()(以及许多其他 Linq 扩展方法)。

【讨论】:

    【解决方案2】:

    这样试试;

    var guids = (List<Guid>) Session["OtherProgramIDs"];
    if (guids != null)
    {
        var guidsStr = guids.Select(x => x.ToString()).ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 2020-12-13
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多