在 expandoObject 列表中搜索

Search in list of expandoObject

假设我有一个 List 动态对象,例如:

var records = [
  {
    "Id": 1,
    "Name": "sai",
    "Age": "4",
    "About": "12.02.1991"
  },
{
    "Id": 2,
    "Name": "hjfh",
    "Age": "2",
    "About": "12.02.1991"
  },
{
    "Id": 3,
    "Name": "hello name",
    "Age": "6",
    "About": "hi"
  },
{
    "Id": 4,
    "Name": 1,
    "Age": "9",
    "About": "hello world"
  }
]

string searchString = "Hello";

我试过类似的方法:

foreach (var item in records )
{

    foreach (var field in item)
    {
        if (field.Value != null && field.Value.ToString().IndexOf(query.SearchString, StringComparison.OrdinalIgnoreCase) >= 0) 
        {
            count++;
            break;
        }
    }
}

我想要在记录的任何字段中具有 searchString 的记录数。但是我可以使用 LINQ 查询来写这个吗?

它会是这样的: 逻辑:

var qry = records.Where(x=>x.Field.Contains(searchedstring)).Count();

实例:

var qry = records.Where(x=>x.Name.Contains("sai")).Count();

这是您的代码,已转换为 linq 表达式:
您可以访问 select 语句中的字段和对象。

    records.Cast<ExpandoObject>().SelectMany(x => x, (obj, field) => new { obj, field })
        .Where(x => x.field.Value != null && x.field.Value.ToString().IndexOf(SearchString, StringComparison.OrdinalIgnoreCase) >= 0)
        .Select(x => x.field.Key);

计算至少有一个字段包含搜索字符串的对象的数量:

    records.Cast<ExpandoObject>()
        .Where(x => x.Any(y => y.Value != null && y.Value.ToString().IndexOf(SearchString, StringComparison.OrdinalIgnoreCase) >= 0))
        .Count();

下面是最简单的代码。

int count = records.Count(x => x.Name.StartsWith("hello") || x.About.StartsWith("hello"));