Hello there!
Once upon a time, somebody told me the notion which “LINQ can do anything!”
For those who have not yet used LINQ, the basis of it is to transform a collection (e.g. arrays, lists) into another form of collection, or filter out from a collection.
So what needs to be done in order to use it? I will have faith in which almost everybody knows how to use SQL. We don’t need to do anything complicated, just on a very base level of knowledge will be fine. Keywords that should be familiar are from, where, select
.
Let’s jump to it. Say that we have a list of strings with such names:
Hugh, Lisa, Shawn, Pamela, Anthony
Now let’s say we want to filter out Pamela. For most Java only thinkers who would probably write a method to do that (I used to be such a person myself), which looks like
public List FilterFromNames(List originalList, string filterName)
{
var list = new List();
foreach (var name in originalList)
{
if (name != filterName)
{
list.Add(name);
}
}
return list;
}
We will be returned a new collection modified from the original list that we have passed in, and say we called var modifiedList = FilterFromNames(myList, "Pamela");
. However in any production-code, we’ll want to try and avoid something like the above since if we’re just going to make a function for one thing, then it should be something viable like passing in a username and password field for different applications.
Instead, we can use LINQ for pretty much the same purpose. Let’s do that and try and get an understanding of an under layer of how it works. There are two types of LINQ: method and comprehension.
In method syntax, we’ll rewrite the above like so:
var modifiedList = myList.Where(name => name != "Pamela").Select(name => name).ToList();
Let’s look at what’s happening here. Since LINQ supports any collection and using any of its methods will return an IEnumerable collection type, our modifiedList is just that as we are calling Where()
. Within our function argument, we have a lambda with a variable which we call “name”, and we’ve also explicitly said it is not the same as “Pamela”. From here, we’ve done a selection by calling Select()
, also returning an IEnumerable. We also have a lambda with a variable called “name” here, and we return everything that we need as the selection is run.
Really, we don’t care what variable is named in our lambda functions, but I purposely made it readable for viewers. However, we can write it like this and still yield the same result:
var modifiedList = myList.Where(x => x != "Pamela").Select(y => y).ToList();
Or, if any reason it is preferred to write comprehensively, this will yield the same result:
var modifiedList = from x in myList where x != "Pamela" select x;
And there you have LINQ in a nutshell! 🙂
Until next time!
Brian.