如果为空,则将其设置为linq中的空字符串lambda表达式
本文关键字:字符串 表达式 linq lambda 如果 设置 | 更新日期: 2023-09-27 18:05:06
我有一个foreach循环,看起来像这样:
foreach (var item in listOfFieldNames)
{
list.Where(s => s.GetType().GetProperty(item).GetValue(s, null).ToString().ToLower().Contains(searchString.ToLower()));
}
,它工作得很好,但每当"s"是null时,我得到nullreferenceexception
我想改变我的s = null为s = " "但我不知道如何做到这一点。你们能帮帮我吗?或者有一种方法可以跳过空记录继续循环而不会出现异常。这对我也有帮助。
试图找出这个相当长一段时间,无法找到答案:/尝试了一些。defaultifempty组合,但我不知道该在里面放什么
如果s有时为null,您可以使用:
list.Where(s => s != null && s.GetType().GetProperty(item).GetValue(s, null).ToString().ToLower().Contains(searchString.ToLower()));
后编辑
问题是GetValue
返回null。在这种情况下,您可以使用空合并操作符??
。我个人会将表达式展开,这样更容易阅读:
list.Where(s =>
{
var property = s.GetType().GetProperty(item);
var value = property.GetValue(s, null);
if (value == null) return false;
return value.ToString().Contains(searchString, StringComparison.OrdinalIgnoreCase);
});
在循环之前从列表中删除null
引用:
list.RemoveAll(s => s == null);
// doing the .ToLower() on searchString before the query will improve performance.
// The original form would execute each pass (as a note .ToUpper() is slightly faster for
// conversions and comparisons since upper case letter come before lower case.
searchString = searchString.ToLower();
// assuming `list` is a List<T> this will allow the inner type of be used to get the
// property list. It is possible to check that getters exist for the properties which
// may be helpful if you have any setter only properties. If you work with any languages
// other than C# you may also want to exclude properties with indexers.
var properties = list.GetType()
.GetGenericArguments()[0].GetProperties()
.Where(p => listOfFieldNames.Contains(p.Name))
.ToList();
var query = from listItem in list
// if you have any setter only properties p.GetValue() will cause an exception
let values = properties.Select(p => p.GetValue(listItem))
.Where(p => p != null)
// you probably don't see the null coalesce but it is possible that .ToString()
// was over ridden and could allow null. The empty string is simplier to inline
// than to add another null filter after the .ToString()
.Select(p => (p.ToString() ?? "").ToLower())
// this will allow you to compare all properties that had values to your search
where values.Contains(searchString)
select listItem;
// this will create a new list that will contain all of the values from list that had at
// least one property that matched your searc hstring
var matched = query.ToList();