将项添加到Linq到SQL IQueryable

时间:2014-10-15 23:34:26

标签: c# sql linq generics dynamic

我正在尝试将项目添加到IQueryable结果中。

我目前按以下方式执行:

 var company_none = new[] {
                         new {
                            company_id = (int?)null,
                            descr = "<NONE>"
                         }};


            var company_result = (from c in companies
                               select new
                               {
                                   c.company_id,
                                   c.descr
                               });

 var result = company_none.Concat(company_result)

我想创建一个接受类型的方法,并根据传递给它的类型动态创建“company_none”。当然,类型将确定匿名类型将包含哪些属性。我用字典尝试过ExpandoObject但它不会识别null。如果属性为null,它只是删除它。简而言之,如何在运行时动态创建像“company_none”这样的匿名类型对象?

提前致谢...

1 个答案:

答案 0 :(得分:0)

方法:

public static class MyEnumerable
{
    public static IEnumerable<T> Append<T>(this IEnumerable<T> input, Dictionary<string, object> parameters)
    {
        var constructor_parameters = typeof(T).GetConstructors()[0].GetParameters().Select(p => p.Name).ToArray();

        if (parameters.Count != constructor_parameters.Length) throw new ArgumentException("Passed parameters count differs from real property count.");
        if (constructor_parameters.Any(p => !parameters.ContainsKey(p))) throw new ArgumentException("Some of properties are not present in a dictionary.");

        var newobject = new T[] { (T)Activator.CreateInstance(typeof(T), constructor_parameters.Select(name=>parameters[name]).ToArray()) };
        return input.Concat(newobject);
    }
}

用法:

var data = new string[]{ "5", "6" }.Select(i => new { a = 2, b = i });
var newprops = new Dictionary<string, object> { { "a", 8 }, { "b", "test" } };

var res = data.Append(newprops).ToArray();