1

Consider the following examples, in all of which, I am trying to get the code and the name of a province/state having a known ID, into a single string variable, with a format like "CA-California":

string stateName = _repository.States.Single(s => s.StateId == stateId).Name;
string stateCode = _repository.States.Single(s => s.StateId == stateId).Code;
string stateCodeName = stateCode + "-" + stateName;


var state = _repository.States.Single(s => s.StateId == stateId);
string stateCodeName = state.Code + "-" + state.Name;  


string stateCodeName = _repository.States.Where(s => s.StateId == stateId)
                                         .Select(s => s.Code + "-" + s.Name)
                                         .First();

In the first example, only the needed properties of the state are retrieved, but at the cost of running two different queries. The second example runs one query only, but it retrieves all of the properties of the state. The third example seems to be all right, but my question is if there is a way to use Single and First methods to retrieve an arbitrary number of properties from an object (or columns from a table), as opposed to getting them all or only one at a time?

Thank You

2 Answers 2

1

my question is if there is a way to use Single and First methods to retrieve an arbitrary number of properties from an object (or columns from a table), as opposed to getting them all or only one at a time?

You can use an anonymous type to do this:

var state = _repository.States.Where(s => s.StateId == stateId)
     .Select(s => new { Code = s.Code, Name = s.Name })
     .First();

This will return an anonymous type with two properties: Code and Name.

(Whether you use First() or Single() depends on how you want the program to behave if there is more than one match. Single() would throw an exception if there was more than one.)

Sign up to request clarification or add additional context in comments.

Comments

0

If you were to change the use of First() to Single() in your third example, you would have exactly the query you're looking for.

The query would return only the single result that you're expecting and would only return the fields (already concatenated) that you're interested in.

1 Comment

Thank you very much for your quick answer Justin. It seems that use of Where method in such a scenario is inevitable, because something like Select method is not available for neither Single nor First.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.