Общий метод расширения типа ToMultidimensionalArray - PullRequest
1 голос
/ 08 июня 2011

В настоящее время я пытаюсь преобразовать IEnumerable<T> в двумерный массив типа T2, используя метод расширения с универсальными типами.Вы также должны иметь возможность выбрать, какие свойства T вы хотите включить в этот массив.

Вот что я получил до сих пор:

public static T2[][] ToMultidimensionalArray<T, T2>(this IEnumerable<T> enumerable, int count, params string[] propNames)
    {
        IEnumerator<T> enumerator = enumerable.GetEnumerator();
        T2[][] resultArray = new T2[count][];
        int i = 0;
        int arrLength = propNames.Length;
        while (enumerator.MoveNext())
        {
            resultArray[i] = new T2[arrLength];
            int j = 0;
            foreach(string prop in propNames)
            {
                resultArray[i][j] = ((T)enumerator.Current).//How do I access the properties?
                j++;
            }
            i++;
        }
        return resultArray;
    }

У меня проблема с доступом к свойствамenumerator.Current внутри foreach -Coop.

Я использую .NET-Framework 4.0.

Любой вклад будет принят с благодарностью.

Спасибо,

Денис

Ответы [ 2 ]

2 голосов
/ 08 июня 2011

В общем, эту проблему можно решить с помощью отражения:

public static T2[][] ToMultidimensionalArray<T, T2>(
                                                this IEnumerable<T> enumerable,
                                                int count,
                                                params string[] propNames)
{
    T2[][] resultArray = new T2[count][];
    int i = 0;
    int arrLength = propNames.Length;
    foreach (var item in enumerable)
    {
        resultArray[i] = new T2[arrLength];
        int j = 0;
        foreach (string prop in propNames)
        {
            // Get the required property info using reflection
            var propertyInfo = typeof(T).GetProperty(prop);
            // Extract the getter method of the property
            var getter = propertyInfo.GetGetMethod();
            // Invoke the getter and get the property value
            var value = getter.Invoke(item, null);
            // Cast the value to T2 and store in the array
            resultArray[i][j] = (T2) value;
            j++;
        }
        i++;
    }
    return resultArray;
}

Я понял проблему как коллекцию T s, в которой эти объекты имеют свойства типа T2. Цель состоит в том, чтобы взять свойства каждого объекта и поместить их в многомерный массив. Поправь меня, если я ошибаюсь.

1 голос
/ 08 июня 2011

Вы имеете в виду (T2) typeof (T) .GetProperty (prop) .GetValue (enumerator.Current, null);

Но я не могу понять, чего ты хочешь. Я не думаю, что этот метод может работать.

...