I have a database table called Customers. I run the following sql to get information about the first and second customer:
select FirstCustomerName, SecondCustomerName, * from Customers where FirstCustomerName = SecondCustomerName
When I run this in sql it gives me what I want, so that one is ok. The problem is when I want to do the same thing in Linq
in C#.
To achive the same thing with Linq I have tried this(still “doesn’t work”):
InfoAboutBothCustomers = c.customers.FirstCustomerName == c.customers.SecondCustomerName.ToString()
Note: InfoAboutBothCustomers is an int in my ViewModel
So my question basically is how do the same thing in LINQ?
Advertisement
Answer
I am not sure what value you want in InfoAboutBothCustomers
. Your SQL statement returns two values and you are saying that you want an int. c.customers.FirstCustomerName == c.customers.SecondCustomerName.ToString()
will return a boolean to say if they are equal or not.
If you want the id or ids that match you criteria, try something like:
var ids = from cust in customers where cust.FirstCustomerName == cust.SecondCustomerName select cust.Id;
Alternatively you can use what is mentioned in the other answers, which is cleaner, but just be aware that FirstOrDefault
will return the row of data. You can then specify the column that you want by doing something like this FirstOrDefault().Id;