[英]What is the type of this inner join LINQ query?
當程序員使用var
而不是精確並編寫正確的類型時,我非常煩惱。 在Microsoft教程中: http : //msdn.microsoft.com/zh-cn/library/bb397927.aspx我已經找到了內部連接的說明(如下)。 innerJoinQuery
的類型可能是什么,因為它看起來像是2個字符串的混搭,但我們不知道結果類型是什么。
引用:
連接操作會在未在數據源中顯式建模的序列之間創建關聯。 例如,您可以執行聯接以查找具有相同位置的所有客戶和分銷商。 在LINQ中,join子句始終直接針對對象集合而不是數據庫表。
C#
var innerJoinQuery =
from cust in customers
join dist in distributors on cust.City equals dist.City
select new { CustomerName = cust.Name, DistributorName = dist.Name };
在LINQ中,不必像在SQL中那樣頻繁地使用join,因為LINQ中的外鍵在對象模型中表示為保存項集合的屬性。 例如,一個Customer對象包含Order對象的集合。 無需執行聯接,而是使用點符號訪問訂單:
編輯:讓我們改寫這個問題。 我還能在這里代替var
放什么呢?
該linq查詢的結果是具有兩個屬性的匿名類型的對象序列 。 其中一個稱為CustomerName
,另一個稱為DistributorName
。 它們都是很有可能是string
類型的。
為了避免var
,您必須使用以下兩個屬性聲明一個類,如下所示:
class ClassName
{
public string CustomerName { get; set; }
public string DistributorName { get; set; }
}
然后,您必須將linq查詢更改為以下查詢:
IEnumerable<ClassName> innerJoinQuery = from cust in customers
join dist in distributors
on cust.City equals dist.City
select new ClassName
{
CustomerName = cust.Name,
DistributorName = dist.Name
};
但是,如果您想獲取此查詢的結果並遍歷它們或其他內容,則上述方法沒有任何好處。 換句話說,我認為var
在這里使用正確。 我的意思是,這不會對您的工作造成任何歧義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.