C# – Selecting a single item with linq2sql query

clinqlinq-to-sql

I'm trying to retrieve a single entity from a Linq2Sql query, but I'm having trouble finding the 'pretty' way of doing it. Here's what I've found that works:

 var states = from state in dc.States where state.Id == j.StateId select state;
State s = states.ToList<State>().ToList()[0];

I'm hoping this isn't the best way of getting the entity. 😛

Anyone have a better solution?

Thanks in advance!

–J

Best Answer

try this:

int stateID = getTheStateIDToLookup();    
State state = dc.States.SingleOrDefault(s => s.StateID == stateID);