如何从Linq查询返回匿名字段

时间:2014-09-30 12:18:02

标签: c# linq

我想从Linq查询中获取匿名字段。我的查询是

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
}

现在 P.MobileNo 是匿名的,我也想返回它。我无法更改myProduct类中的任何内容。

谁知道怎么做?

谢谢

3 个答案:

答案 0 :(得分:3)

您需要使用匿名类型

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

或者创建另一个包含MobileNo属性的命名类型。如果您需要从方法中返回

答案 1 :(得分:2)

创建一个将继承myProduct的类。

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

在Linq:

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

答案 2 :(得分:2)

您可以将myProduct对象和P.MobileNo包装成匿名类型:

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