Wednesday, October 26, 2016

LINQ ABCs

Having learned C# 2.0 first, for the longest time I just wrote foreach loops and would let ReSharper refactor them into LINQ or Lambda shapes. More recently, I've gotten pretty confident in writing Lambda expressions. LINQ seems to come up for less simplistic refactorings, but I was looking over this on Monday and it's really not rocket science. If you can write T-SQL you can write LINQ. It sure feels similar. Observe:

var whatever = from person in people
select person;
 

Obviously, what's above is a simple select. If we have an IEnumerable or List of Person in people then we would comically be just getting an IEnumerable of the same stuff. Clearly we need to filter. We do that like so, and again this is gonna look a lot like T-SQL...

var whatever = from person in people
where person.FirstName == "Clive"
select person;
 

Use double ampersands or double pipe symbols in the where clauses for and/or logic in filtering Clive records. Order the Clives like so:

var whatever = from person in people
where person.FirstName == "Clive"
orderby person.LastName descending
select person;
 

The let keyword is for a midstream transformation!

var whatever = from person in people
let maybedutches = person.LastName.Split(' ')
from maybedutch in maybedutches
where maybedutch == "Van"
select person;
 

I had heard that joins are pretty painful in Entity Framework and since the selects are all LINQ statements I can see why! Look at this:

var whatever = from person in people
join phone in phones on phone.Number equals person.Phone
select new { Name = person.FirstName, Country = phone.Country };
 

Well yuck, anonymous types! Yeesh! The first link I provide also goes into some esoteric groupings. Basically you can break a collection into a collection of collections all sorted out by something-er-other. You end up with an IEnumerable<IGrouping<string, Person>> which is straying beyond that which is common and simple.

No comments:

Post a Comment