如何使用LINQ从动态列表中选择特定字段

时间:2019-02-20 09:41:58

标签: c# linq system.linq.dynamic

我试图从动态对象中获取某些特定字段,实际上是任何类的列表,此类包含那些字段中的各种字段,我想使用LINQ选择某些特定字段,我想选择的字段也被用户传递。下面是我尝试使用System.Linq.Dynamic的代码。

using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Linq.Dynamic;
using System.Collections;

private void Test_Click(object sender, EventArgs e)
{
            List<RateInfo> lst = new List<RateInfo>();
            lst.Add(new RateInfo() { id_country = "IND", id_state = 1, rate = 2.3f });
            lst.Add(new RateInfo() { id_country = "IND", id_state = 2, rate = 1.1f });
            lst.Add(new RateInfo() { id_country = "IND", id_state = 3, rate = 5.2f });
            lst.Add(new RateInfo() { id_country = "IND", id_state = 4, rate = 6.5f });

        GetDynamicData(lst, new List<string>() { "id_country", "id_state" });
}

    private void GetDynamicData(dynamic list, List<string> fetchFields)
    {

        var data = ((IEnumerable)list).Cast<dynamic>()
                        .Select(r => new { r }).AsQueryable();

        StringBuilder s = new StringBuilder();

        //This is for test only. 
        //It works, the value of "id_state" and "id_state" getting appended 
        foreach (var item in data)
        {
            s.Append(item.r.id_state);
            s.Append(",");
            s.Append(item.r.id_country);
        }
        //-----------------------------------------------------


        //Select the specific field data from dynamic list 
        StringBuilder fields = new StringBuilder();

        fields.Append("new (");

        foreach (var fld in fetchFields)
        {
            fields.Append("r." + fld);
            fields.Append(",");
        }
        fields.Remove(fields.Length - 1, 1);
        fields.Append(")");

        //This does not work throws error 
        //"No property or field 'id_country' exists in type 'Object'"
        IQueryable iq = data.Select(fields.ToString());

        //For test only to check the value of selected fields
        foreach (dynamic item in iq)
        {
            s.Append(item.id_state);
            s.Append(",");
            s.Append(item.id_country);
        }

    }

2 个答案:

答案 0 :(得分:1)

您应该尝试使用generics

private void GetDynamicData<T>(IEnumerable<T> list, List<string> fetchFields)
{

    var data = list.AsQueryable();

答案 1 :(得分:0)

您可以简化GetDynamicData方法,既可以指定显式列表类型(GetDynamicData(IList<RateInfo> list, ...)),又可以使列表项类型保持通用,以便重用该方法;考虑到最后一种方法,您可以按如下所示重写GetDynamicData,以获得所需的输出:

    private void GetDynamicData<T>(IEnumerable<T> list, List<string> fetchFields)
        {
            var fields = $"new ({string.Join(",", fetchFields)})";
            var res = list.AsQueryable().Select(fields);

            //For test only to check the value of selected fields
            foreach (dynamic item in res) {
                Console.WriteLine(item.id_state);
                Console.WriteLine(item.id_country);
            }

        }

输出

1
IND
2
IND
3
IND
4
IND

解释 我认为区别在于,明确指定类型(通过通用T或通过RateInfo)使LINQ知道列表项的类型。如果您使用dynamic实例的IQueryable.ElementType的{​​{1}}值为IQuqryable,则查询将因您遇到的错误而失败。