eom*_*off -4 c# linq collections
如何查询类型T的集合,返回T的所有项,其中任何T的属性包含一些字符串?
编辑:
假设我在检查包含之前将每个属性转换为字符串.
你的意思是这样的?
list.Any(x => x.GetType()
.GetProperties()
.Any(p =>
{
var value = p.GetValue(x);
return value != null && value.ToString().Contains("some string");
}));
Run Code Online (Sandbox Code Playgroud)
如果只获取类型和属性一次,这可能会更有效:
var type = list.GetType().GetGenericArguments()[0];
var properties = type.GetProperties();
var result = list.Any(x => properties
.Any(p =>
{
var value = p.GetValue(x);
return value != null && value.ToString().Contains("some string");
}));
Run Code Online (Sandbox Code Playgroud)
注意:如果要检查任何属性是否包含某些字符串,请使用Any,如果您还希望获取与您的条件匹配的项目,请使用Where方法而不是第一个Any.使用list.Where(x => properties.Any(...));
| 归档时间: |
|
| 查看次数: |
3020 次 |
| 最近记录: |