IQueryable OfType where T is a runtime Type

后端 未结 7 610
旧巷少年郎
旧巷少年郎 2020-12-14 01:52

I need to be able to get something similar to the following to work:

Type type = ??? // something decided at runtime with .GetType or typeof;
object[] entity         


        
7条回答
  •  时光取名叫无心
    2020-12-14 02:35

    what about ...

        public static IList OfTypeToList(this IEnumerable source, Type type)
        {
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            return
                (IList) Activator.CreateInstance(
                    typeof(List<>)
                       .MakeGenericType(type),
                    typeof(System.Linq.Enumerable)
                       .GetMethod(nameof(System.Linq.Enumerable.OfType),
                                  BindingFlags.Static | BindingFlags.Public)
                       .MakeGenericMethod(type)
                       .Invoke(null, new object[] { source }));
        }
    

提交回复
热议问题