Создать generi c Linq extension Метод "сшивания" данных по ключу - PullRequest
0 голосов
/ 01 августа 2020

У меня есть набор курсов (идентификатор, имя, статус, инструктор и т. Д. c) и еще один набор цен (CourseId, цена).

Я пытаюсь написать метод расширения linq для объединить эти два вместе, но мое отражение немного ржавое. Что мне не хватает?

Я хочу назвать это так:

courses.SewData(pricing, p => p.Id, c => c.CourseId);

Это вызываемый метод. У меня проблемы с ToDictionary Line. Это не компилирование. Как мне создать словарь с моим существующим выражением

public static class DataExtension {
    public static IEnumerable<TParent> SewData<TParent, TChild>(this IList<TParent> parentCollection, IList<TChild> childCollection, Expression<Func<TParent, object>> parentProperty, Expression<Func<TChild, object>> childProperty) {

        var parentPropertyInfo = ReflectionHelper.GetProperty(parentProperty);
        var childPropertyInfo = ReflectionHelper.GetProperty(childProperty);

        var parentDict = parentCollection.ToDictionary(parentProperty, x => x); //need help here
        foreach (var child in childCollection) {
            var childId = childPropertyInfo.GetValue(child);
            var parentItem = parentDict[childId];
            
            //use reflection here to map properties by name
            

            
            yield return parentItem;
        }          
    }
}

1 Ответ

2 голосов
/ 01 августа 2020

Я бы сказал, что вам не нужны выражения и отражение для этой части, вы можете попробовать что-то вроде этого (также добавлен параметр TKey generi c для типа ключа):

public static class DataExtension {
    public static IEnumerable<TParent> SewData<TParent, TChild, TKey>(
         this IList<TParent> parentCollection, 
         IList<TChild> childCollection, 
         Func<TParent, TKey> parentKeySelector, 
         Func<TChild, TKey> childKeySelector) {

        var parentDict = parentCollection.ToDictionary(parentKeySelector); 
        foreach (var child in childCollection) {
            var childId = childKeySelector(child);
            var parentItem = parentDict[childId];
            
            //use reflection here to map properties by name             
              
            yield return parentItem;
        }          
    }
}

if вам все равно понадобятся выражения позже по какой-то другой причине, вы можете использовать Compile, чтобы получить parentKeySelector из parentProperty.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...