How do I pass function delegates to be called with LINQ? [closed]

北城以北 提交于 2020-01-13 14:01:10

问题


I think I'm asking the right question here...

I have 4 stored procedures that return different subsets of the same data.

I map this data to the same object in my server application.

I've set my code up as follows:

internal static MyDataContext dc = new MyDataContext();

internal static List<MyObj> getData(DataType data)
{
    List<MyObj> obj = null;
    switch (data) 
    {
        case DataType.Type1:
            obj = mapObj(dc.getDataType1);
            break;
        case DateType.Type2:
            obj = mapObj(dc.getDataType2);
            break;
        ...
    }
}

// This gives me an error that type T cannot be defined
// private static List<MyObj> mapObj(Func<T> getDataForObj)
// This gives me an error calling the function (Cannot find implementation of query pattern for source type T
private static List<MyObj> mapObj<T>(Func<T> getDataForObj)
{
    List<MyObj> obj = new List<MyObj>();

    var result = from a in getDataForObj()
                 select a;

    foreach (var row in result)
    {
        ... // map objs 
    }    

    return obj;
}

Please see my comments regarding the method declaration for the issues I'm having. How would I accomplish this correctly? My goal was to just not have the same code copy/pasted multiple times...trying to follow DRY principles. Thanks in advance for your help.


回答1:


Making my mapObj function as follows (Per @Jon Skeet's recommendation in the comments) allowed it to compile and run:

private static List<MyObj> mapObj<T>(Func<IEnumerable<T>> getDataForObj)
{
    List<MyObj> obj = new List<MyObj>();

    var result = from a in getDataForObj()
                 select a;

    foreach (var row in result)
    {
        ... // map objs 
    }    

    return obj;
}

This led to a new problem regarding the mapping of the fields, but I will ask that in a new question.



来源:https://stackoverflow.com/questions/6747797/how-do-i-pass-function-delegates-to-be-called-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!