簡體   English   中英

如何在 linq 中進行內部選擇?

[英]How do I do an inner select in linq?

我有一個名為客戶的數據庫表。 我運行以下 sql 以獲取有關第一個和第二個客戶的信息:

select FirstCustomerName, SecondCustomerName, 
* from Customers where FirstCustomerName = SecondCustomerName

當我在 sql 中運行它時,它給了我我想要的東西,所以一個沒問題。 問題是當我想在 C# 中的Linq中做同樣的事情時。

為了用 Linq 達到同樣的效果,我試過這個(仍然“不起作用”):

   InfoAboutBothCustomers = c.customers.FirstCustomerName == c.customers.SecondCustomerName.ToString()

注意:InfoAboutBothCustomers 在我的 ViewModel 中是一個int

所以我的問題基本上是如何在 LINQ 中做同樣的事情?

沒有樣品很難提供任何解決方案。 但是你可以試試這個

InfoAboutBothCustomers = c.customers.Where(x=>x.FirstCustomerName == x.SecondCustomerName).FirstOrDefault()

如果出現錯誤/問題,請分享示例。

使用.Where操作

InfoAboutBothCustomers = c.customers.Where(c => c.FirstCustomerName == c.SecondCustomerName).FirstOrDefault();

我不確定您在InfoAboutBothCustomers想要什么值。 您的 SQL 語句返回兩個值,並且您說您想要一個 int。 c.customers.FirstCustomerName == c.customers.SecondCustomerName.ToString()將返回一個布爾值來說明它們是否相等。

如果您想要符合您條件的 id 或 id,請嘗試以下操作:

var ids = from cust in customers
          where cust.FirstCustomerName == cust.SecondCustomerName
          select cust.Id;

或者,您可以使用其他答案中提到的內容,這更清晰,但請注意FirstOrDefault將返回數據行。 然后,您可以通過執行類似FirstOrDefault().Id;類的操作來指定所需的列FirstOrDefault().Id;

暫無
暫無

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

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