Get selected fields on a list using a LINQ query

1.6k views Asked by At

I have an entity framework generated class like this.

public partial class TBLM_PRODUCT
{
    public string PRODUCT_CODE { get; set; }
    public string PRODUCT_DESC { get; set; }
    public string PRODUCT_ISBN { get; set; }
    public string PRODUCT_SUPPLIER { get; set; }
    public string PRODUCT_PROGROUP { get; set; }
}

Normally I select items list like this using a LINQ query.

using ( AEntities RAEntity = new AEntities())
{
    RAEntity.TBLM_PRODUCT.ToList<DataControllers.TBLM_PRODUCT>();
}

I want to select an item list with two fields like this like as in following query

 select PRODUCT_CODE,PRODUCT_DESC from TBLM_PRODUCT where PRODUCT_PROGROUP='GG';

How can I achieve that?

3

There are 3 answers

0
nemanja228 On
using ( AEntities RAEntity = new AEntities())
{
    var all = RAEntity.TBLM_PRODUCT.ToList<DataControllers.TBLM_PRODUCT>();
    var yourList = all
        .Where(x => x.PRODUCT_PROGROUP == "GG")
        .Select(p => new { p.PRODUCT_CODE, p.PRODUCT_DESC })
        .ToList();
}
0
er-sho On

Don't select all records first and then filtered your data.

If you use .ToList<DataControllers.TBLM_PRODUCT>() then it can select all records. So instead of this you can select your columns at the time of query fired to database.

If your TBLM_PRODUCT is of any collection type like IEnumerable<> or IQueryable<> then,

using ( AEntities RAEntity = new AEntities())
{
    var result = RAEntity.TBLM_PRODUCT.Where(x => x.PRODUCT_PROGROUP == "GG").Select(x => new { x.PRODUCT_CODE, x.PRODUCT_DESC }).ToList();
}
1
iDark On
using (AEntities RAEntity = new AEntities())
{
    var list= RAEntity.TBLM_PRODUCT
        .Where(p => p.PRODUCT_PROGROUP == "GG")
        .Select(p => new TBLM_PRODUCT { PRODUCT_CODE = p.PRODUCT_CODE, PRODUCT_DESC = p.PRODUCT_DESC })
        .ToList();
}