开发者

Generic method using linq expressions

I have the next 2 methods:

        public static string[] Method1(CustomObj co)
        {
            return new string[] {co.X,co.Y };
        }

        public static string[][] Method2(IQueryable<CustomObj> cos)
        {
            string[][] s = new stri开发者_运维技巧ng[cos.Count()][];
            int i = 0;
            foreach (var co in cos)
            {
                s.SetValue(Method1(co), i);
                i++;
            }
            return s;
        }

I want to make a generic method instead of Method2, something like

static string[][] Method2(this IQueryable query, string method1Name)

Any tips?

Thanks.


It looks to me like you can just do:

string[][] ret = query.Select(x => Method1(x)).ToArray();

or

string[][] ret = query.Select<CustomObject, string[]>(Method1).ToArray();

in the first place without needing to write your extra method at all. Any reason not to do this? If you really need it to take a method name then you'd need to use some reflection - but I'd advise you to avoid this in the first place if at all possible.


What you want is using Method 1 as a delegate.

public delegate string[] MyDelegate<T>(T obj);

public static string Method2<T>(this IQueryAble<T> cos, MyDelegate<T> function1)
{
   string[][] s = new string[cos.Count()][];
   int i = 0;
   foreach (var co in cos)
   {
      s.SetValue(function1(co), i);
      i++;
   }
}


Do you have to pass in a string for the method name? That isn't trivial.

Most of the LINQ extension methods take a lambda for the method to call:

public static string[][] Method2(this IQueryable<CustomObj> cos, Func<CustomObj, string[]> func)        
{            
    string[][] s = new string[cos.Count()][]; 
    int i = 0;            
    foreach (var co in cos)            
    {                
         s.SetValue(func(co), i);
         i++;            
    }
    return s;        
}

Then you can call it like this:

 iqueryableobject.Method2(x => Method1(x));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜