将GUID的会话变量列表转换为字符串列表

问题描述 投票:0回答:2

我有一个会话变量,它被设置为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的定义,没有扩展方法选择接受类型对象的第一个参数可以找到”:

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

这给了我同样的信息:

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

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

编辑

我已经添加了上面的错误消息。还从评论中尝试了这个建议,并收到了有关System.Collections.Generic.List yada yada yada的相同突出显示的错误。

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

仅供参考 - 这个GUID可以为空,这是正常的,还有其他限制因素可以解决这个问题。

c# list
2个回答
4
投票

几乎在那里,首先你需要将Session对象映射到IEnumerable<System.Guid?>,然后在每个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();

最后但并非最不重要的是,Linq使用了界面IEnumerable<T>,它可以使用.Select().Where()(在许多其他Linq扩展方法中)。


0
投票

试试这样;

var guids = (List<Guid>) Session["OtherProgramIDs"];
if (guids != null)
{
    var guidsStr = guids.Select(x => x.ToString()).ToList();
}
© www.soinside.com 2019 - 2024. All rights reserved.