【问题标题】:How do I do an inner select in linq?如何在 linq 中进行内部选择?
【发布时间】:2021-09-19 15:17:30
【问题描述】:

我有一个名为“客户”的数据库表。我运行以下 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 中做同样的事情?

【问题讨论】:

    标签: c# sql linq linq-to-sql


    【解决方案1】:

    我不确定您想要 InfoAboutBothCustomers 中的什么值。您的 SQL 语句返回两个值,并且您说您需要一个 int。 c.customers.FirstCustomerName == c.customers.SecondCustomerName.ToString() 将返回一个布尔值来表示它们是否相等。

    如果您想要一个或多个符合您条件的 id,请尝试以下操作:

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

    或者,您可以使用其他答案中提到的内容,这样更简洁,但请注意 FirstOrDefault 将返回数据行。然后,您可以通过执行类似 FirstOrDefault().Id;

    的操作来指定所需的列

    【讨论】:

      【解决方案2】:

      没有样本很难提供任何解决方案。不过你可以试试这个

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

      如果出现错误/问题,请分享示例。

      【讨论】:

        【解决方案3】:

        使用.Where操作

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-08
          相关资源
          最近更新 更多