Преобразуйте IEnumerable в DataTable

Похоже, вам нужно количество дней для определенного периода времени. Если я правильно понимаю:

select count(*) as num_user_days_in_range
from (select a.username, date_trunc('day', ah.modified) as login_date
      from accounts a join
           account_history ah
           on modified_acc_id = a.id
      where ah.data::jsonb->>'message' = 'Logon'
      group by a.username, login_date
     ) u
where login_date >= $date1 and login_date < $date2
63
задан Community 23 May 2017 в 12:25
поделиться

4 ответа

Посмотрите на этот: Преобразовать List / IEnumerable в DataTable / DataView

В моем коде я изменил его на метод расширения:

public static DataTable ToDataTable<T>(this List<T> items)
{
    var tb = new DataTable(typeof(T).Name);

    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach(var prop in props)
    {
        tb.Columns.Add(prop.Name, prop.PropertyType);
    }

     foreach (var item in items)
    {
       var values = new object[props.Length];
        for (var i=0; i<props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }

    return tb;
}
99
ответ дан 24 November 2019 в 16:18
поделиться

Так, 10 лет спустя это - все еще вещь:)

я попробовал каждый ответ на этой странице (ATOW)
, и также некоторый ILGenerator привел в действие решения ( FastMember и Быстро. Отражение ).
, Но скомпилированное Лямбда-выражение, кажется, является самым быстрым.
, По крайней мере, для моих вариантов использования (на.Net Core 2.2).

Это - то, что я использую на данный момент:

public static class EnumerableExtensions {

    internal static Func<TClass, object> CompileGetter<TClass>(string propertyName) {
        var param = Expression.Parameter(typeof(TClass));
        var body = Expression.Convert(Expression.Property(param, propertyName), typeof(object));
        return Expression.Lambda<Func<TClass, object>>(body,param).Compile();
    }     

    public static DataTable ToDataTable<T>(this IEnumerable<T> collection) {
        var dataTable = new DataTable();
        var properties = typeof(T)
                        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                        .Where(p => p.CanRead)
                        .ToArray();

        if (properties.Length < 1) return null;
        var getters = new Func<T, object>[properties.Length];

        for (var i = 0; i < properties.Length; i++) {
            var columnType = Nullable.GetUnderlyingType(properties[i].PropertyType) ?? properties[i].PropertyType;
            dataTable.Columns.Add(properties[i].Name, columnType);
            getters[i] = CompileGetter<T>(properties[i].Name);
        }

        foreach (var row in collection) {
            var dtRow = new object[properties.Length];
            for (var i = 0; i < properties.Length; i++) {
                dtRow[i] = getters[i].Invoke(row) ?? DBNull.Value;
            }
            dataTable.Rows.Add(dtRow);
        }

        return dataTable;
    }
}

Только работы со свойствами (не поля), но это работает над Анонимными Типами.

0
ответ дан 24 November 2019 в 16:18
поделиться

В afaik нет ничего встроенного, но собрать его самому должно быть легко. Я бы сделал то, что вы предлагаете, и использовал бы отражение, чтобы получить свойства и использовать их для создания столбцов таблицы. Затем я бы прошел по каждому элементу в IEnumerable и создал для каждого строку. Единственное предостережение: если ваша коллекция содержит элементы нескольких типов (скажем, человек и животное), они могут иметь разные свойства. Но если вам нужно это проверить, это зависит от вашего использования.

0
ответ дан 24 November 2019 в 16:18
поделиться

Выражение в основном идентично:

if ( (cat != null && cat.getColor() == "orange") || cat.getColor() == "grey") {
  ...
}

Здесь порядок приоритета таков, что AND ( & & ) имеет более высокий приоритет, чем OR ( | | ).

Вы также должны знать, что использование = = для проверки Последовательности равенства будет иногда работать в Java, но это не так, как вы должны делать это. Вы должны сделать:

if (cat != null && ("orange".equals(cat.getColor()) || "grey".equals(cat.getColor()))) {
  ...
}

то есть использовать методы equals () для сравнения Последовательностей , а не = , который просто ссылается на равенство. Ссылочное равенство для последовательностей может вводить в заблуждение. Например:

String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
-121--1009761-

Предположим, что ваша таблица продуктов называется Product, а столбец ID в этой таблице называется Id:

SELECT * from Product p where p.Id IN 
  (Select id_product from ProductAttributes where id_attribute in (21, 23, 24))
-121--3690434-

Для всех:

Обратите внимание, что принятый ответ содержит ошибку, относящуюся к типам со значениями NULL и Исправление доступно на связанном сайте ( http://www.chinhdo.com/20090402/convert-list-to-datatable/ ) или в моем измененном коде ниже:

    ///###############################################################
    /// <summary>
    /// Convert a List to a DataTable.
    /// </summary>
    /// <remarks>
    /// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "ToDataTable"
    /// <para/>Code modifications made by Nick Campbell.
    /// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
    /// <para/>Copyright © 2010 Chinh Do
    /// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    /// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    /// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    /// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
    /// </remarks>
    /// <typeparam name="T">Type representing the type to convert.</typeparam>
    /// <param name="l_oItems">List of requested type representing the values to convert.</param>
    /// <returns></returns>
    ///###############################################################
    /// <LastUpdated>February 15, 2010</LastUpdated>
    public static DataTable ToDataTable<T>(List<T> l_oItems) {
        DataTable oReturn = new DataTable(typeof(T).Name);
        object[] a_oValues;
        int i;

            //#### Collect the a_oProperties for the passed T
        PropertyInfo[] a_oProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            //#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
            //####     NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
        foreach(PropertyInfo oProperty in a_oProperties) {
            oReturn.Columns.Add(oProperty.Name, BaseType(oProperty.PropertyType));
        }

            //#### Traverse the l_oItems
        foreach (T oItem in l_oItems) {
                //#### Collect the a_oValues for this loop
            a_oValues = new object[a_oProperties.Length];

                //#### Traverse the a_oProperties, populating each a_oValues as we go
            for (i = 0; i < a_oProperties.Length; i++) {
                a_oValues[i] = a_oProperties[i].GetValue(oItem, null);
            }

                //#### .Add the .Row that represents the current a_oValues into our oReturn value
            oReturn.Rows.Add(a_oValues);
        }

            //#### Return the above determined oReturn value to the caller
        return oReturn;
    }

    ///###############################################################
    /// <summary>
    /// Returns the underlying/base type of nullable types.
    /// </summary>
    /// <remarks>
    /// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "GetCoreType"
    /// <para/>Code modifications made by Nick Campbell.
    /// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
    /// <para/>Copyright © 2010 Chinh Do
    /// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    /// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    /// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    /// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
    /// </remarks>
    /// <param name="oType">Type representing the type to query.</param>
    /// <returns>Type representing the underlying/base type.</returns>
    ///###############################################################
    /// <LastUpdated>February 15, 2010</LastUpdated>
    public static Type BaseType(Type oType) {
            //#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
        if (oType != null && oType.IsValueType &&
            oType.IsGenericType && oType.GetGenericTypeDefinition() == typeof(Nullable<>)
        ) {
            return Nullable.GetUnderlyingType(oType);
        }
            //#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
        else {
            return oType;
        }
    }

Обратите внимание, что оба этих примера являются НЕ методами расширения, как в примере выше.

Наконец... извинения за мои обширные/чрезмерные комментарии (у меня был анальный/средний проф., который избил меня!;)

17
ответ дан 24 November 2019 в 16:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: