Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ : Generics with IQueryable

I have to add some "lookup" queries to my C#.NET application. Basically, there will be many tables where they all have the same schema, but contain different values.

I am faced with writing the same code over and over (should be an OO way to do this..)

[edit - below is modified to show more complete info] Anyways, what I would like to do is:

public List<GenericLookupE>         GetLookupItems( string what )
{
    // create db thing
    if ( "regions" == what )  return FetchLookup( db.lkRegions.AsQueryable() );
    if ( "partners" == what ) return FetchLookup( db.lkPartners.AsQueryable() );
    if ( "funders" == what )  return FetchLookup( db.lkFunders.AsQueryable() );

    return null; // or something more intelligent than that =)
}


private List<GenericLookupE>        FetchLookup<T>( IQueryable<T> lookup )
{
    return lookup.OrderBy( p => p.Sequence ).Select
    (   p => new GenericLookupE()
        {
            ID      = p.ID
            ,Label      = p.Label
            ,StateCode  = p.StateCode
            ,Sequence   = p.Sequence
        }
    ).ToList();
}

of course, the problem is the compiler doesn't know what 'p => p.Sequence' is. Any ideas?

Thank you all.

like image 605
horace Avatar asked Dec 15 '11 16:12

horace


2 Answers

Type constraints on generics are your friend. With a base type or interface containing Sequence:

where T : IMyBaseInterface

http://msdn.microsoft.com/en-us/library/bb384067.aspx

like image 178
Sheridan Bulger Avatar answered Oct 13 '22 15:10

Sheridan Bulger


Add a common interface to your Т classes, define Sequence there, and add a constraint to your generic requiring Т parameters to implement the common interface.

interface ICommonInterface { // This is an awful name, please pick something better
    int Sequence { get }
}

private List<GenericLookupE> FetchLookup<T>( IQueryable<T> lookup ) where T : ICommonInterface {
    // Your stuff here
}
like image 32
Sergey Kalinichenko Avatar answered Oct 13 '22 13:10

Sergey Kalinichenko