Click here to Skip to main content
15,877,915 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,


I am novice to LINQ.
I want the following SQL query to be in LINQ:-
C#
string strSql = "SELECT FULLNAME FROM Contact  WHERE ContactID IN (" + wherecondition + ")";



Please help.


Thanks
Posted
Updated 23-Jun-15 1:07am
v3

Here is a great resource for getting started with linq

https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b[^]
 
Share this answer
 
The issue is that you have to insist that there is only one result. You can use .Single() if you know there are no more and no less than 1 result:

C#
string name = db.Contacts.Single(c=>c.ContactID == contactId)

if there are 0 to 1 then use .FirstOrDefault which would return null if there are 0 results.

Otherwise you can use a where clause to select an enumeration, from which you can select out the field you want using .Select():
C#
string[] name = db.Contacts.Where(c=>contactIds.Contains(c.ContactID)).Select(c=>c.FullName).ToArray()



Hope that helps ^_^
Andy
 
Share this answer
 
Comments
Nathan Minier 23-Jun-15 7:37am    
I would highly suggest using FirstOrDefault() for both performance and resiliency purposes. Single (and SingleOrDefault) enumerates the entire collection so that if there are more than 1 matching entry, an exception is thrown.

Single is good for integrity checks, but bad for queries.
Richard Deeming 23-Jun-15 8:20am    
Not quite. The overloads of Single and SingleOrDefault which don't take a predicate will only enumerate a maximum of two items in the collection - if there is a second item, they throw an exception immediately, rather than enumerating the rest of the collection.

You can see this in the source code[^].

When translated to SQL, it will issue a SELECT TOP 2 ... query.
Nathan Minier 23-Jun-15 8:56am    
I'll happily concede that point, in that instance. I'm not sure that it makes it preferential to First(OrDefault), though. Is there a compelling reason that the First for query, Single for integrity rule is wrong?
Richard Deeming 23-Jun-15 9:03am    
If you only ever expect your query to return a single item, then it's a good idea to validate that assumption; otherwise, your code might proceed to do the wrong thing, and you won't know until it's too late.

Rather than splitting into query / integrity, I'd say use First when you don't care if there's more than one match, and Single when you do care.
Andy Lanng 23-Jun-15 9:17am    
I concede that rule-of-thumb

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900