开发者

Is it possible to format the results of a query using a Lambda Expression?

开发者 https://www.devze.com 2023-04-09 07:58 出处:网络
Let\'s say I have this query I pass to a repository: var results = userRepository.Get(u => u.Username == \"JDoe\" && u.Password == \"123456\");

Let's say I have this query I pass to a repository:

var results = userRepository.Get(u => u.Username == "JDoe" && u.Password == "123456");

Now, let's say I create an expression to format the results a certain way:

Expression<Func<User,strin开发者_开发百科g>> userDisplay = u => u.Firstname + " " + u.LastName + " - " + u.CompanyName

So I may have to write my own extension, but something like this:

var formatedResults = results.Format(userDisplay);

Update:

What about a more complicated solution to project the results into another object:

public class SearchResult
{
     object EntityId {get; set;}
     object Displaytext {get; set;}

}

So, using the same idea to use the specific display expression, what is a good way to project the results into the SearchResult object?


you should be able to just call

Update As noted in the comments Select doesn't accept an Expression argument. Unless userDisplay needs to be an expression it could just be updated as a delegate:

Func<User,string>> userDisplay = u => u.Firstname + " " + u.LastName + " - " + u.CompanyName;

var formatedResults = results.Select(userDisplay);

Update

Select allows you to transform whatever you are iterating over.

Some examples of what you could do:

var formattedResults = results.Select(x=> new SearchResult { EntityId = x.Id, DisplayText = userDisplay(x){);
//anonymous type
var formattedResults = results.Select(x=> new { EntityId = x.Id, DisplayText = x.ToString()});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号