如何使用动态构建的lambda表达式搜索动态对象IEnumerable <dynamic>?

时间:2017-04-08 16:46:59

标签: c# linq lambda where dynamicobject

以前,我对上一个问题的帮助很大,谢谢vyrpHow do I create and populate a dynamic object using a dynamically built lambda expression

我现在正在寻找搜索动态对象,和以前一样,我不知道对象属性,因此我一直在搜索运行时。

以下是构建动态对象的代码:

        // Get list of optional fields
        var optFieldList = await _tbList_FieldRepository.GetAsync(lf => lf.ListID == listId && lf.DisplayInList == true);
        // order list of optional fields
        optFieldList.OrderBy(lf => lf.DisplayOrder);

        // Get base Data excluding Inactive if applicable
        IEnumerable<tbList_Data> primaryData = await _tbList_DataRepository.GetAsync(ld => ld.ListID == listId && (ld.IsActive == includeInactive ? ld.IsActive : true));

        // Build IEnumerable<dynamic> from base results plus any optional fields to be displayed in table   
        var results = primaryData.Select(pd => {
            dynamic result = new System.Dynamic.ExpandoObject();
            result.Id = pd.ID;
            result.PrimaryData = pd.PrimaryData;
            result.DisplayOrder = pd.DisplayOrder;
            result.IsActive = pd.IsActive;
            foreach (var optField in optFieldList)
            {
                switch (optField.FieldType.ToLower()) {
                    case "text":
                        ((IDictionary<string, object>)result).Add(optField.FieldName, pd.tbList_DataText.Where(ld => ld.DataRowID == pd.ID && ld.ListColumnID == optField.ID).Select(ld => ld.DataField).DefaultIfEmpty("").First());
                        break;
                }
            }
            return result;
        });

出于测试目的,我有2个动态字段,“PhoneNumber”和“FuelType”

我可以搜索已知字段,即PrimaryData,没问题,如下所示。

        results = results.Where(r => r.PrimaryData.Contains(searchString));

如果我在设计时知道PhoneNumber字段

,以下内容将有效
        results = results.Where(r => r.PhoneNumber.Contains(searchString));

但我想做的是:

results = results.Where(r => r.PrimaryData.Contains(searchString) 
    || foreach(var optField in optFieldList)
    {
        r.optField.FieldName.Contains(searchString)
    })

结尾
results = results.Where(r => 
    r.PrimaryData.Contains(searchString) 
    || r.PhoneNumber.Contains(searchString) ||    
    r.FuelType.Contains(searchString));

但显然代码不起作用。我尝试过一系列不同的尝试,没有成功,所以我在寻找建议。感谢

1 个答案:

答案 0 :(得分:3)

由于您知道查询的dynamic元素实际上是ExpandoObject,因此IDictionary<string, object>>,您可以安全地将其转换为字典界面并使用它来按名称访问属性值,Enumerable.Any方法可用于模拟动态||条件:

results = results.Where(r => r.PrimaryData.Contains(searchString)
    || optFieldList.Any(f =>
    {
        object value;
        return ((IDictionary<string, object>)r).TryGetValue(f.FieldName, out value)
            && value is string && ((string)value).Contains(searchString);
    }));