C# LINQ filtering

LINQ (Language Integrated Query) is a .NET methodology for query. Beside using LINQ we can also do this by using for, while loops.

List<string> items = new List<string>() { "berkay", "yaylaci", "test1", "blog", "firstpost", "blabla" };

There is list of strings and I need to get strings that include “ay”. First, we can do this by using for loop.

string singleLineResult = "";
for(int i = 0; i < items.Count; i++)
{
   string tempItem = items[i];
   if(tempItem.Contains("ay")) // we have checked all the elements that contains "ay" string.
   {
      singleLineResult += tempItem + " ";
   }
}
Console.WriteLine(singleLineResult);

We can see that for loop is capable of doing this as well 🙂

Let’s try this with LINQ. We need to use Where() method which accepts the source and second parameter accepts a criteria. Actually this method loop the source inside and returns the result according to given criteria. Our criteria is -> containing “Ay”.

var result = items.Where(x => x.Contains("ay")).ToList();

If we don’t call ToList() it won’t project the result set into List<T> type. It will generate IEnumerable<T>.

Now we can show the result on console but first we need a fancy output. So lets seperate each of them with space.

var singleLineResult = string.Join(" ", result);

Then, write to the console!

Console.WriteLine(singleLineResult);