开发者

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

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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 g开发者_如何转开发ives 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜