tags:

views:

106

answers:

3

Hello, 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 string[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 IQuerable, string method1Name) Any tips? Thanks.

A: 

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));
Matt Breckon
+1  A: 

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.

Jon Skeet
A: 

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++;
   }
}
Sebastian P.R. Gingter
Thanks a lot, problem solved
bogus