简体   繁体   中英

using Single/First methods to return multiple values in linq or lambda expression

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

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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM