private static IEnumerable EnumerateList([NotNull] object list, [NotNull] ListDescriptor listDescriptor) { var count = listDescriptor.GetCollectionCount(list); for (var i = 0; i < count; i++) { yield return(listDescriptor.GetValue(list, i)); } }
/// <summary> /// Tries to convert the <paramref name="sourceList"/> to the type described by <paramref name="listDescriptor"/>. /// </summary> /// <param name="sourceList"></param> /// <param name="listDescriptor"></param> /// <param name="convertedList"></param> /// <returns><c>true</c> if the <paramref name="sourceList"/> could be converted to the type described by <paramref name="listDescriptor"/>; otherwise, <c>false</c>.</returns> private static bool TryConvertListData([NotNull] object sourceList, [NotNull] ListDescriptor listDescriptor, out object convertedList) { try { var sourceListType = sourceList.GetType(); // Already same type if (listDescriptor.Type == sourceListType) { convertedList = sourceList; return(true); } convertedList = Activator.CreateInstance(listDescriptor.Type, true); var sourceListDescriptor = (ListDescriptor)TypeDescriptorFactory.Default.Find(sourceListType); foreach (var item in EnumerateList(sourceList, sourceListDescriptor)) { object obj; if (!TypeConverterHelper.TryConvert(item, listDescriptor.ElementType, out obj)) { // (optimistic) try to convert the remaining items continue; } listDescriptor.Add(sourceList, obj); } return(listDescriptor.GetCollectionCount(convertedList) > 0); } catch (InvalidCastException) { } catch (InvalidOperationException) { } catch (FormatException) { } catch (NotSupportedException) { } catch (Exception ex) when(ex.InnerException is InvalidCastException) { } catch (Exception ex) when(ex.InnerException is InvalidOperationException) { } catch (Exception ex) when(ex.InnerException is FormatException) { } catch (Exception ex) when(ex.InnerException is NotSupportedException) { } // Incompatible type and no conversion available convertedList = null; return(false); }