top of page

Fun With LINQ


Microsoft .NET LINQ

Hey kids!!


It never fails, there's always that one super easy thing that we forget. It's very basic and one of the fundamental things you've learned about C#, and should make sense in our brains, but this one thing most certainly doesn't stick.


All of us have that one function or object that seems to be forgotten as soon as its used. Until you need it again in a week, month, year.



So, here's the one aggravatingly easy LINQ Microsoft .NET statement I always have to look up because I forget how to write it ...


Every. Single. Time.




You need to pull from a list, using 2 parameters to search with.


Example:
Get a list of People objects that have a last name of Smith and they live in Sussex.

The Cure band


Is it easy??


Yes.


Do I still forget it??


100%


I always want to write it incorrectly like this:



var resultPeopleList = peopleList.Where(x => x.LastName == "Smith") && (x => x.State == "CA").ToList();

I really don't know why I want to write it like this, but I do. It's reminiscent of joining two requirements in an 'if' statement, which is not LINQ.


The correct way to write it is like this:


var resultPeopleList = peopleList.Where(x => x.LastName == "Smith" &&  x.State == "CA").ToList();

Then you can use a foreach loop if you need to do something to each resulting record. If the list has no results, the foreach will exit itself.


foreach (var person in resultPeopleList )
        {
           person.LastName;
        }

Hopefully you will see this once and remember for the rest of your career!! I wish that for each of you <3


The question remains if I will ever remember this without looking it up ... it seems like it should be something I remember since I do use it a lot .... but I don't.


I blame gangsta rap from the '90's sticking in my head instead of code .... but for real, those lyrics are still FIRE



PEACE OUT




bottom of page