简体   繁体   中英

how to return anonymous field from Linq query

I want to get anonymous field from Linq query.My query is

from p in product
Select new myProduct
{
  id = p.Id,
  Name = p.Name,
  P.MobileNo
}

//Here is myProduct class 

class myProduct
{
   public int Id,
   public string Name
}

Now here P.MobileNo is anonymous and I also want to return that.I cannot change anything in myProduct class.

anyone know how to do this ?

Thanks

You will need to use an anonymous type

from p in product
select new
{
  p.Id,
  p.Name,
  p.MobileNo
}

Or create another named type that contains MobileNo property. If you need to return this from a method

Create a class that will inherit from myProduct.

class myProduct
{
   public int Id {get;set;}
   public string Name {get;set;}
}
class mySecondProduct : myProduct
{
   public string MobileNo {get;set;}
}

In Linq:

from p in product
Select new mySecondProduct
{
  id = p.Id,
  Name = p.Name,
  P.MobileNo
}

You could wrap the myProduct object and P.MobileNo in an anonymous type:

from p in product
select new
{
    Product = new myProduct { Id = p.Id, Name = p.Name},
    MobileNo = P.MobileNo
}

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