简体   繁体   中英

Add few properties of class in list

I have a class with 8 properties declared:

public  class  classProduct
{
    public int iProductID { get; set; }
    public string sPName { get; set; }
    public string sPDescription { get; set; }
    public int iPTypeID { get; set; }
    public string sPPrice { get; set; }
    public string sPType { get; set; }
    public string sImagePath { get; set; }
    public string sDestinationPath { get; set; }
}

And I have a method in which I add 4 properties in my list like and ProductDetailsTbls is my Tbl1 and ProductTypeTbls is Tbl2.

public List<classProduct> GetAllProduct()
{ 
    List<classProduct> lst = new List<classProduct>();
    lst = (from c in dc.ProductDetailsTbls
             join d in dc.ProductTypeTbls
             on c.PTypeID equals d.PTypeID
             select new classProduct { sPName=c.PName, sPDescription=c.PDescription, sPPrice=c.PPrice, sPType=d.PType }).ToList();
    return lst;
}

But it returns all properties that I don't want.

If you only want some properties I think you will have to introduce a new class.

My approach for this would be to define a base class with your four properties and then you can classProduct inherit from it.

your base-class then looks like:

public class baseClassProduct
{
    public string sPName { get; set; }
    public string sPDescription { get; set; }
    public string sPPrice { get; set; }
    public string sPType { get; set; }
}

and your classProduct:

public class classProduct : baseClassProduct
{
    public int iProductID { get; set; }
    public int iPTypeID { get; set; }
    public string sImagePath { get; set; }
    public string sDestinationPath { get; set; }
}

In your GetAllProduct-Method you can work with the baseClass and you'll get only the information you want to.

public List<baseClassProduct> GetAllProduct()
{ 
    List<baseClassProduct> lst = new List<baseClassProduct>();
    lst = (from c in dc.ProductDetailsTbls
             join d in dc.ProductTypeTbls
             on c.PTypeID equals d.PTypeID
             select new baseClassProduct { sPName=c.PName, sPDescription=c.PDescription, sPPrice=c.PPrice, sPType=d.PType }).ToList();
   return lst;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM