Is there a way to do something like this:
db.People.Single(x => x.Id = 123).Select(x => new { x.FirstName, x.LastName });
(.Select is an extension method to IEnumerable)
Or do I have to write it as:
db.People.Where(x => x.Id = 123).Select(x => new { x.FirstName, x.LastName }).Single();
Single returns a single object of type People so no, you cannot. You use Select with collections/arrays/lists/etc.
Just do the projection before the Single: People.Select(x => new { }).Single(x => condition)
Also – be VERY sure that you want to use Single () as it can be expensive. It’s meant to ensure that there is only a single thing that passes the predicate. First() or FirstOrDefault() is usually more appropriate, especially if you’re working with a database table – the ID should be unique already.
Initally I thought your example would select every person out the db, and then in-memory match the single. But it’s deferred, right?
I’ve seen bugs with the use of First() when it’s not unique. Something like:
var person = People.First(x => x.Id == 1)
Somebody then does this:
var personWithManager1 = People.First(x => x.ManagerId == 1)
But yeah, any code is open to misuse! 🙂
You can write the extension method yourself like so:
public static TOut Map<TIn, TOut>(this TIn target, Func<TIn, TOut> map)
=> map(target);
I don’t even remember the last time when I wrote such a bullshit, so imma share