Down Below I took part of a code I was looking at. I don’t understand the IEnumerable part of the Code. Can someone just walk me through the meaning of each line. Thanks
I don’t understand the Where(u =>) more than the rest.
public static List<AAlexUsers.Models.SearchClass> Users(string userId, string email, string lastFourdigits)
{
SearchClass Alex = new SearchClass();
Alex.userId = "1234";
Alex.email = "Alex@gmail.com";
Alex.lastFourdigits = "1885";
SearchClass Emilio = new SearchClass();
Emilio.userId = "0928";
Emilio.email = "Cubano@gmail.com";
Emilio.lastFourdigits = "0706";
SearchClass Ulysses = new SearchClass();
Ulysses.userId = "0914";
Ulysses.email = "lysses@gmail.com";
Ulysses.lastFourdigits = "01zx";
var list = new List<SearchClass>();
list.Add(Alex);
list.Add(Emilio);
list.Add(Ulysses);
IEnumerable<SearchClass> result = list;
if (!string.IsNullOrEmpty(userId))
result = result.Where(u => u.userId == userId);
if (!string.IsNullOrEmpty(email))
result = result.Where(u => u.email == email);
if (!string.IsNullOrEmpty(lastFourdigits))
result = result.Where(u => u.lastFourdigits == lastFourdigits);
return list.ToList();
}
The IEnumerable is a collection of SearchClass objects. See it as something like a list or an array.
IEnumerable is a generic interface describing something that can be enumerated (you can iterate through it and see/retrieve all of its elements). The content of this IEnumerable can have been pre-generated, or is live/lazily generated when you try to iterate through ‘result’ (IEnumerable).
The next lines are queries run against this “result’ list:
can be confusing since it assigns the return of the query to the data the query is run on.
Let’s take a simpler example:
means that “var myResult” contains all elements from myEnumerableList, only when this element (here, called ‘u’)has a property userId that is equal to “Yusuf”
.Net provides powerful ways to query collections/lists/anything_enumerable, presented with an SQL-like syntax