在参数中将List<string>转换为IEnumerable<guid>

3

我有一个名为 GetContentPageToValueVo 的函数,它接受类型为 IEnumerable<Guid> 的参数,这里的 locations 和 services 是 list<string> 类型,那么如何将这个参数行转换为 IEnumerable 类型?我的 locations 列表来自 solr,并且以字符串格式具有有效的 GUID。

Location = ScHelper.Instance().GetContentPageToValueVo(x.Locations),
                Service = ScHelper.Instance().GetContentPageToValueVo(x.Services)
1个回答

2
你可以使用LINQ的Select方法和Guid.ParseList<string>转换为IEnumerable<Guid>
这里的Select会:
将序列的每个元素投影到一个新的形式中,并合并元素的索引。
Guid.Parse则会:
将GUID的字符串表示形式转换为等效的Guid结构。
因此你的代码将变成:
Location = ScHelper.Instance().GetContentPageToValueVo(x.Locations.Select(Guid.Parse)),
Service = ScHelper.Instance().GetContentPageToValueVo(x.Services.Select(Guid.Parse))

为了避免ArgumentNullException,你可以使用以下方法:
Guid y;

Location = ScHelper.Instance().GetContentPageToValueVo(x.Locations.Where(x=>!string.IsNullOrWhiteSpace(x) && Guid.TryParse(x,out y)).Select(Guid.Parse)),
Service = ScHelper.Instance().GetContentPageToValueVo(x.Services.Where(x=>!string.IsNullOrWhiteSpace(x) && Guid.TryParse(x,out y)).Select(Guid.Parse))

我该如何进行空值检查并避免在此处引发参数空异常? - Rohan Bhateja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接