有时Resharper会警告:
可能的多个枚举IEnumerable
关于如何处理这个问题还有一个问题,ReSharper网站也在这里解释了一些事情.它有一些示例代码,告诉您这样做:
IEnumerable<string> names = GetNames().ToList();
Run Code Online (Sandbox Code Playgroud)
我的问题是关于这个特定的建议:这不会导致在2 for-each循环中两次枚举集合吗?
有没有一种很好的方法将IEnumerable转换为DataTable?
我可以使用反射来获取属性和值,但这似乎有点低效,是否有内置的东西?
(我知道这些例子:ObtainDataTableFromIEnumerable)
编辑:
这个问题通知我处理空值的问题.
我在下面写的代码正确处理空值.
public static DataTable ToDataTable<T>(this IEnumerable<T> items) {
// Create the result table, and gather all properties of a T
DataTable table = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Add the properties as columns to the datatable
foreach (var prop in props) {
Type propType = prop.PropertyType;
// Is it a nullable type? Get the underlying type
if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
propType = new NullableConverter(propType).UnderlyingType;
table.Columns.Add(prop.Name, propType);
}
// …Run Code Online (Sandbox Code Playgroud) 如何从简单对象的List <>中使用SqlBulkCopy进行大插入?
我是否实现了自定义IDataReader?