如何选择动态列表的值和类型?

问题描述 投票:0回答:1

我有一个动态查询,为我带来了动态列(System.Linq.Dynamic.Core):

var data = data.Select("new (col1, col2, col3)", "T", StringComparison.OrdinalIgnoreCase);
[
   { col1: "This", col2: 1.56, col3: "Something else" }
]

现在,我需要输入每列的类型。例如:

[
   {
      col1: { value: "This", type: "string" },
      col2: { value: 1.56, type: "decimal" }
   }
]

为此,我想到了类似的东西:

var rows = data.Select(x => new {
    Type = MyHelper.GetType(x),
    Value = x
});

但是它不起作用。

发生未处理的错误,最佳匹配方法为'MyHelper.GetType(System.Reflection.PropertyInfo)'有一些无效参数

我知道如何获得类型

public static string GetType(PropertyInfo type)
{
    return type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? type.PropertyType.GetGenericArguments()[0].ToString().Replace("System.", "") : type.PropertyType.Name;
}

但是我不知道如何建立查询。

[更新]

这是尝试,但不是我需要的

var rows = data.Select(x => new {
    Type = MyHelper.GetType(x.GetType()),
    Value = x
});
[
    {
        "type": "<>f__AnonymousType0`3",
        "value": {
            "col1": "2019-10-15T00:00:00",
            "col2": 0.00,
            "col3": "abc"
        }
    },
]
c# linq asp.net-core dynamic-linq
1个回答
0
投票

您需要使用GetProperties()来迭代动态对象的属性:

这里是完整的示例,其工作方式:

GetProperties()

它将为您提供此输出:

static void Main(string[] args)
{
    List<dynamic> data = new List<dynamic>() {

        new { col1 = "This", col2 = 1.56, col3 = "Something else" },
        new { col1 = "This 2", col2 = 1.76, col3 = "Something else 2" }
    };

    var rows = data.Select(x => new
    {
        Prop = (x as Object).GetType()
                            .GetProperties()
                            .Select(p => new
                            {
                                Name = p.Name,
                                Type = GetType(p),
                                Val = p.GetValue(x)
                            }).ToList(),
    });

    foreach (dynamic prop in rows.Select(s => s.Prop))
    {
        foreach (var item in prop)
        {
            Console.WriteLine("Name:" + item.Name + " Type:" + item.Type + " Val:" + item.Val);
        }
        Console.WriteLine("----");
    }

    Console.ReadLine();
}
© www.soinside.com 2019 - 2024. All rights reserved.