Lidprogsky
Lidprogsky

Reputation: 43

How do I do an inner select in linq?

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?

Upvotes: 0

Views: 64

Answers (3)

spmoolman
spmoolman

Reputation: 422

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;

Upvotes: 1

H.Sarxha
H.Sarxha

Reputation: 172

Use .Where operation

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

Upvotes: 1

Amit Verma
Amit Verma

Reputation: 2490

Without sample it is difficult to provide any solution. But you can try this

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

In case of error /issue please share the sample.

Upvotes: 1

Related Questions