提问人:TheProgrammer 提问时间:11/11/2023 最后编辑:TheProgrammer 更新时间:11/11/2023 访问量:51
Linq 查询检查列表是否包含空字符串,然后检查是否为 null
Linq query to check list contains empty string then check for null
问:
我有一个列表,其中可能包含也可能不包含空字符串。如果是这样,我想创建一个 linq 查询来检查 where 子句中的空值,同时检查列表中的其他值并将它们添加到 where 子句中。
这是我现在拥有的 linq 格式,它不检查 null:
if (myList.Count > 0)
{
objects = objects.Where(a => myList.Contains(a.Items));
}
这是我所期望的行为,但想知道是否有办法将其放入 linq 格式或更好的方法?
foreach(var listItem in myList)
{
if (string.IsNullOrEmpty(listItem))
{
//This would only be hit once as myList has a distinct list of values
objects = objects.Where(a => a.Items == null);
}
else
{
objects = objects.Where(a => a.Items == listItem);
}
}
答:
1赞
Salman A
11/11/2023
#1
我想你可以这样写:
objects = objects.Where(o =>
myList.Any(l =>
string.IsNullOrEmpty(l) ? o.items == null : o.items == l
)
)
0赞
TheProgrammer
11/11/2023
#2
这是最适合我的解决方案:
if (myList.Count > 0)
{
if(myList.Contains(string.Empty))
{
objects = objects.Where(a => a.Items == null || myList.Contains(a.Items));
}
else
{
objects = objects.Where(a => a.Items != null && myList.Contains(a.Items));
}
}
评论