locked
How select subset of columns from IQueryable<Type>? RRS feed

  • Question

  • From my business tier (class) I get back an IQueryable<Pen> of data.  Here is my client code that works fine:

     

    PenClass penClass = new PenClass();
    IQueryable<Pen> pens = penClass.SelectPens();


    However, I want to then select a subset of this data from within the client.  I tried this:

     

    IQueryable<Pen> pensSubset = from p in pens select p.PenId, p.PenNumber;

     

    .. but it doesn't even compile.

     

    Can anyone tell me the correct syntax?

     

    Thanks.

     

    Friday, August 8, 2008 2:32 AM

Answers

  • You need to define a class for this purpose:

    public class PenCore { public int PenID, PenNumber }

    and then project into it:

    IQueryable<PenCore> pensSubset =
    from p in pens
    select new PenCore
    {
    PenID = p.PenId,
    PenNumber = p.PenNumber
    };

    You can then return Queryable<PenCore> from your method. Another option is to use an anonymous type, but this is viable only if you don't intend to pass that data between methods.

    Joe
    Friday, August 8, 2008 6:24 AM
  • VB supports the inline select statement as you specified, but C# requires the type initializer syntax Joe mentioned.

     

    Jim Wooley

    www.ThinqLinq.com

    Friday, August 8, 2008 1:45 PM

All replies

  • You need to define a class for this purpose:

    public class PenCore { public int PenID, PenNumber }

    and then project into it:

    IQueryable<PenCore> pensSubset =
    from p in pens
    select new PenCore
    {
    PenID = p.PenId,
    PenNumber = p.PenNumber
    };

    You can then return Queryable<PenCore> from your method. Another option is to use an anonymous type, but this is viable only if you don't intend to pass that data between methods.

    Joe
    Friday, August 8, 2008 6:24 AM
  • VB supports the inline select statement as you specified, but C# requires the type initializer syntax Joe mentioned.

     

    Jim Wooley

    www.ThinqLinq.com

    Friday, August 8, 2008 1:45 PM