Accepted answer

That line is selecting all instances n in nameList where the string n contains the string name. So your result will be any of the strings in nameList that have the string name in it.

Also, it is important to break it up into the two parts. First, this is a Linq query. You could do this to find all the items in nameList that equal name exactly: var filteredStringList = from n in nameList where n == name select n;

Your where statement "n.IndexOf(name, 0, StringComparison.OrdinalIgnoreCase) != -1" just changes the simpler query, "n == name" to filter in a slightly different way. First, the n.IndexOf(name) method gets the first starting index where the string name occurs in n. Any value >= 0 means that name exists in the string. -1 is returned if the string doesnt exist. The other arguments are the index where to start the search, in your case 0, and the string comparison, in your case StringComparison.OrdinalIgnoreCase. StringComparison.OrdinalIgnoreCase tells the string comparison to treat A and a as the same and so on.

Edit: @Jason had a good point to consider also. While strictly speaking the query is not actually doing the iteration, it is actually creating a linq expression. The expression will execute only after you call something like filteredStringList.ToList() or a similar call. For all intents and purposes, the result is the same, but it is important to know when the query will actually execute. See this post for more details:


It's saying if a variable called name exists in nameList then select it into filteredStringList.


"get all entries of nameList which contain name"


Your LINQ can be interpreted as

    for (int i = 0; i < nameList.Count; i++)
          if (nameList[i].IndexOf(name, 0, StringComparison.OrdinalIgnoreCase) != -1) 


here TempList is List<String> TempList = new List<string>();

In LAMBDA Expression you can write this as

var filteredStringList = nameList.Where(X => X.IndexOf(name, 0, StringComparison.OrdinalIgnoreCase) != -1);


var filteredStringList = 
    from n in nameList
    where n.IndexOf(name, 0, StringComparison.OrdinalIgnoreCase) != -1
    select n;

This is LINQ (specifically the query syntax form), and exactly what is happening is a little complicated and subtle.

The rough idea is that this block of code creates an iterator. When this iterator is iterated over, it will filter nameList by only selecting the elements of nameList that satisfy the predicate p(n) = n.IndexOf(name, 0, StringComparison.OrdinalIgnoreCase) != -1. That is, it will only select the elements of nameList that contain name (ignoring case).

It is very important that you understand that filteredStringList is not a list (thus, it is horribly named). It does not contain the results of the filtering. It only creates an object that captures the rules for building the filtered subsequence of nameList when it is iterated over.

Related Articles