如果一个字段为空,我如何用Linq替换一个值
本文关键字:一个 何用 Linq 替换 字段 如果 | 更新日期: 2023-09-27 18:25:43
我有以下报告:
var menuItems = _menuRepository.GetPk(pk)
.Where(m => m.Status == "00")
.OrderBy(m => m.Order)
.Select(m => new MenuItem
{
PartitionKey = m.PartitionKey,
RowKey = m.RowKey,
Order = m.Order,
Order1 = m.Order.Substring(0, 1),
Order2 = m.Order.Substring(2, 1),
Order3 = m.Order.Substring(4, 1),
Order4 = m.Order.Substring(6, 2),
Title = m.Title,
Type = m.Type,
Link = m.Link,
TextLength = m.TextLength
});
如果某些记录的Order为null或为空,则此操作将失败。如果m。Order为null或为空,有没有办法用一个零代替所有Order.Substrings?
您可以使用空合并运算符:
var menuItems = _menuRepository.GetPk(pk)
.Where(m => m.Status == "00")
.OrderBy(m => m.Order)
.Select(m =>
{
var orderOrEmpty = m.Order ?? "00000000";
return new MenuItem
{
PartitionKey = m.PartitionKey,
RowKey = m.RowKey,
Order = m.Order,
Order1 = orderOrEmpty.Substring(0, 1),
Order2 = orderOrEmpty.Substring(2, 1),
Order3 = orderOrEmpty.Substring(4, 1),
Order4 = orderOrEmpty.Substring(6, 2),
Title = m.Title,
Type = m.Type,
Link = m.Link,
TextLength = m.TextLength
};
});
如果null
或为空,听起来您想用0替换m.Order.SubString
调用的结果。这样做的方法是,如果m.Order
值为null/空,则只使用所有0的字符串
.Select(m => {
var order = m.Order ?? "00000000";
return new MenuItem {
PartitionKey = m.PartitionKey,
RowKey = m.RowKey,
Order = m.Order,
Order1 = order.Substring(0, 1),
Order2 = order.Substring(2, 1),
Order3 = order.Substring(4, 1),
Order4 = order.Substring(6, 2),
Title = m.Title,
Type = m.Type,
Link = m.Link,
TextLength = m.TextLength
}});
Order1 = m.Order == null ? "0" : m.Order.Substring(0, 1)
条件运算符(?:)也称为三元运算符,根据布尔表达式的值返回两个值中的一个。
<boolean condition> ? <value returned if true> : <value returned if false>;
Order1 = (m.Order ?? "00000000").Substring(0, 1)
或
Order1 = string.IsNullOrEmpty(m.Order) ? "0" : m.Order.Substring(0, 1)
我将编写一个扩展方法IfNotNull
并用作
m.Order.IfNotNull(s=>s.Substring(0,1),"0")
//or
m.Order.IfNotNull(s=>s.Substring(6,2),"00")
//or
m.Order.IfNotNull(s=>s.Substring(6,2))
public static class MyExtensions
{
public static TOut IfNotNull<T, TOut>(this T target, Func<T, TOut> valueFunc,TOut defValue=default(TOut))
where T : class
{
return target == null ? defValue : valueFunc(target);
}
}