General extension method with custom return type

I am trying to write an extension method for two objects.

First find the type of the object, then do an inner join with another table.

If it's type A, then Join should be with B. If it's type B, then join A. But I'm stuck in Join state.

 public static C GetAllInfo<T>(this IQueryable<T> objCust) { if (typeof(T) == typeof(B)) { //prepare the Object based on the Type var objCastReg = objCust as IQueryable<B>; //how to write join here ????? var objUsermaster=objCastReg.GroupJoin(A,um=>um.UserId,r=>r.) //Build the Class object from two retrieved objects. } if (typeof(T) == typeof(A)) { var objCast = objCust as IQueryable<A>; } return null; } public class C { public AA{ get; set; } public BB{ get; set; } } 
+4
source share
1 answer

It sounds like you shouldn't use generics at all. Generics are when your generic method doesn't need to know the type. The generic type parameter signals that this method can work with any particular type.

Perhaps for both cases you should have only two methods with special workarounds. This makes all casting and complexity go away.

But if you insist on a universal method, here's how to do it. First create the special case that I talked about.

 public static C GetAllInfo(this IQueryable<A> objCust); //implement this public static C GetAllInfo(this IQueryable<B> objCust); //implement this 

Then tell them:

 public static C GetAllInfo<T>(this IQueryable<T> objCust) { if (typeof(T) == typeof(B)) { return GetAllInfo((IQueryable<B>)objCust); //call to specialized impl. } if (typeof(T) == typeof(A)) { return GetAllInfo((IQueryable<A>)objCust); //call to specialized impl. } //fail } 
+6
source

Source: https://habr.com/ru/post/1495732/


All Articles