加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – IEnumerable到T []的数组

发布时间:2020-12-15 23:42:25 所属栏目:百科 来源:网络整理
导读:问题标题可能不正确.我有以下变量 IEnumerable x = // some IEnumerableSystem.Type y = // some type 如何迭代x以生成具有y类型项的数组? 当我查看互联网时,我发现: public T[] PerformQueryT(IEnumerable q){ T[] array = q.CastT().ToArray(); return a
问题标题可能不正确.我有以下变量

IEnumerable x = // some IEnumerable
System.Type y = // some type

如何迭代x以生成具有y类型项的数组?

当我查看互联网时,我发现:

public T[] PerformQuery<T>(IEnumerable q)
{                         
        T[] array = q.Cast<T>().ToArray();
        return array;
}

注意我不能调用那个方法PerformQuery因为类型为System.Type,换句话说就是把它称为PerformQuery< typeof(y)>(x);或PerformQuery< y>(x);会给我一个编译器错误.

编辑

这就是我遇到这个问题的原因.我有网络服务,我发布了两件事.我想要查询的表的类型(示例typeof(Customer)),以及实际的字符串查询示例“Select * from customers”

protected void Page_Load(object sender,EventArgs e)
    {
        // code to deserialize posted data
        Type table = // implement that here
        String query = // the query that was posted

        // note DB is of type DbContext
        IEnumerable q = Db.Database.SqlQuery(table,query );

        // here I will like to cast q to an array of items of type table!

解决方法

您可以使用表达式树:

public static class MyExtensions
{
    public static Array ToArray(this IEnumerable source,Type type)
    {
        var param = Expression.Parameter(typeof(IEnumerable),"source");
        var cast = Expression.Call(typeof(Enumerable),"Cast",new[] { type },param);
        var toArray = Expression.Call(typeof(Enumerable),"ToArray",cast);
        var lambda = Expression.Lambda<Func<IEnumerable,Array>>(toArray,param).Compile();

        return lambda(source);
    }
}

它生成x => x.Cast< Type>().ToArray(),在运行时已知Type.

用法:

IEnumerable input = Enumerable.Repeat("test",10);
Type type = typeof(string);

Array result = input.ToArray(type);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读