簡體   English   中英

如何從Linq查詢返回匿名字段

[英]how to return anonymous field from Linq query

我想從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類中的任何內容。

有人知道怎么做嗎 ?

謝謝

您需要使用匿名類型

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

或創建另一個包含MobileNo屬性的命名類型。 如果需要從方法中返回此值

創建一個將繼承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
}

您可以將myProduct對象和P.MobileNo包裝為匿名類型:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM