diff --git a/MoreLinq/ToDataTable.cs b/MoreLinq/ToDataTable.cs index 249488619..59a42b4fd 100644 --- a/MoreLinq/ToDataTable.cs +++ b/MoreLinq/ToDataTable.cs @@ -189,20 +189,6 @@ static MemberInfo[] BuildOrBindSchema(DataTable table, MemberInfo[] members) var columns = table.Columns; - var schemas = from m in members - select new - { - Member = m, - Type = (m.MemberType == MemberTypes.Property - ? ((PropertyInfo)m).PropertyType - : ((FieldInfo)m).FieldType) switch - { - var type when Nullable.GetUnderlyingType(type) is { } t => t, - var type => type, - }, - Column = columns[m.Name], - }; - // // If the table has no columns then build the schema. // If it has columns then validate members against the columns @@ -211,25 +197,34 @@ var type when Nullable.GetUnderlyingType(type) is { } t => t, if (columns.Count == 0) { - columns.AddRange(schemas.Select(m => new DataColumn(m.Member.Name, m.Type)).ToArray()); + foreach (var member in members) + _ = columns.Add(member.Name, GetElementaryTypeOfPropertyOrField(member)); + + return members; } - else - { - members = new MemberInfo[columns.Count]; - foreach (var info in schemas) - { - var member = info.Member; - var column = info.Column ?? throw new ArgumentException($"Column named '{member.Name}' is missing.", nameof(table)); + var columnMembers = new MemberInfo[columns.Count]; - if (info.Type != column.DataType) - throw new ArgumentException($"Column named '{member.Name}' has wrong data type. It should be {info.Type} when it is {column.DataType}.", nameof(table)); + foreach (var member in members) + { + var column = columns[member.Name] ?? throw new ArgumentException($"Column named '{member.Name}' is missing.", nameof(table)); - members[column.Ordinal] = member; - } + if (GetElementaryTypeOfPropertyOrField(member) is var type && type != column.DataType) + throw new ArgumentException($"Column named '{member.Name}' has wrong data type. It should be {type} when it is {column.DataType}.", nameof(table)); + + columnMembers[column.Ordinal] = member; } - return members; + return columnMembers; + + static Type GetElementaryTypeOfPropertyOrField(MemberInfo member) => + (member.MemberType == MemberTypes.Property ? ((PropertyInfo)member).PropertyType + : ((FieldInfo)member).FieldType) + switch + { + var type when Nullable.GetUnderlyingType(type) is { } ut => ut, + var type => type, + }; } static Func CreateShredder(IEnumerable members)