转义空值 LINQ
Escape null values LINQ
我对这个 linq 表达式有疑问:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => sitecoreContext.GetItem<Inv>(new ID(x).Guid))
.ToList();
如何检查 .Select 中的空值? SitecoreContext.GetItem(new ID(x).Guid)) 崩溃(因为项目未发布,或创建但未发布)所以我需要一种方法来首先验证该项目是否存在,然后才使 select.
谢谢。
您可以在 Linq 示例中使用 null 合并运算符或三元运算符检查 Null
`var productTypes = from ProductDto e in Product
select new
{
Id = e.Product != null ? e.Product.ID : 0,
Name = "xyz"
};`
当您调用 SitecoreContext.GetItem<T>
时,在后台 SitecoreContext
从数据库中获取项目,然后将其转换为 T 类型。据我所知,如果没有指定 ID 的项目,它会抛出异常。
为了避免这个异常,你可以做的是拆分 SitecoreContext
所做的事情,然后自己执行它,并在两者之间进行空检查:
- 先执行
GetItem
- 做空检查
- 将项目投射到您的类型:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => sitecoreContext.Database.GetItem(new ID(x)))
.Where(x => x != null)
.Select(x => sitecoreContext.Cast<Inv>(x))
.ToList();
您可以使用 where
语句过滤所有非空项目。
var nonNull = list.Where(element => element != null);
我通常为此使用扩展方法:
public static class EnumerableExtensions
{
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> enumerable)
where T: class
{
return enumerable.Where(element => element != null);
}
}
根据您的示例,您可以使用如下语句:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.WhereNotNull()
.Select(x => sitecoreContext.GetItem<Inv>(new ID(x).Guid))
.ToList();
我对这个 linq 表达式有疑问:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => sitecoreContext.GetItem<Inv>(new ID(x).Guid))
.ToList();
如何检查 .Select 中的空值? SitecoreContext.GetItem(new ID(x).Guid)) 崩溃(因为项目未发布,或创建但未发布)所以我需要一种方法来首先验证该项目是否存在,然后才使 select.
谢谢。
您可以在 Linq 示例中使用 null 合并运算符或三元运算符检查 Null
`var productTypes = from ProductDto e in Product
select new
{
Id = e.Product != null ? e.Product.ID : 0,
Name = "xyz"
};`
当您调用 SitecoreContext.GetItem<T>
时,在后台 SitecoreContext
从数据库中获取项目,然后将其转换为 T 类型。据我所知,如果没有指定 ID 的项目,它会抛出异常。
为了避免这个异常,你可以做的是拆分 SitecoreContext
所做的事情,然后自己执行它,并在两者之间进行空检查:
- 先执行
GetItem
- 做空检查
- 将项目投射到您的类型:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => sitecoreContext.Database.GetItem(new ID(x)))
.Where(x => x != null)
.Select(x => sitecoreContext.Cast<Inv>(x))
.ToList();
您可以使用 where
语句过滤所有非空项目。
var nonNull = list.Where(element => element != null);
我通常为此使用扩展方法:
public static class EnumerableExtensions
{
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> enumerable)
where T: class
{
return enumerable.Where(element => element != null);
}
}
根据您的示例,您可以使用如下语句:
var invs = ids.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries)
.WhereNotNull()
.Select(x => sitecoreContext.GetItem<Inv>(new ID(x).Guid))
.ToList();