B. Clay Shannon B. Clay Shannon - 1 month ago 18
C# Question

How can I return just a single class instance from a SQLite query?

I've got this SQLite code to try to retrieve a record:

String qry = String.Format("SELECT ChallengeTypeFK, {0}, {1} FROM LettersWordPhrases WHERE Id = ?", keyLang, candidateAnswersLang);
List<DBModels.LettersWordsPhrases> lwp = dbConn.Query<DBModels.LettersWordsPhrases>(qry, randomId);


I would prefer to just assign the results of the query to a single DBModels.LettersWordsPhrases, but it says that's not possible, that it needs a List<> . Why would that be necessary, when I only want to return one record?

How can I get it to just return one record, rather than have to extract the first (and only) element from the result set?

Answer

You can use Enumerable.FirstOrDefault()

String qry = String.Format("SELECT ChallengeTypeFK, {0}, {1} FROM LettersWordPhrases WHERE Id = ?", keyLang, candidateAnswersLang); 
DBModels.LettersWordsPhrases lwp = dbConn.Query<DBModels.LettersWordsPhrases>(qry, randomId).FirstOrDefault();

Remember to check if lwp is null, in case no record was returned.