LINQ stands for Language Integrated Query, it provides extension methods that are super useful when iterating through collections of entities. Below are some of the common and useful LINQ methods I have used while taking advantage of its Fluent API (This just means it returns a reference to the original object.)
Generally I don’t like to use temporary variables like x in the predicate, I find it easier to read if the variable is named in a manner that representing the state. Example: if the _fooRepository was _clientRepository then x could be substituted with cl or client.
Select
Projects each element of a sequence into a new form.
- Returns
IEnumerablewhose elements are the result of invoking the transform function on each element of source. So the below will return anIEnumerable<int>containing theId's.
1 | var foos = _fooRepository |
Where
Filters a sequence of values based on a predicate.
- Returns
IEnumerablethat contains elements from the input sequence that satisfy the condition.
1 | var foos = _fooRepository |
GroupBy
Groups the elements of a sequence according to a specified key selector function.
- Returns
IEnumerable<IGrouping<TKey, TSource>>
1 | var fooGroupsOfMemberA = _fooRepository |
Contains
Determines whether a sequence contains a specified element by using the default equality comparer.
- Returns
trueif the source sequence contains an element that has the specified value; otherwise,false.
In the example below bars is some IEnumerable collection, the entity has a property UserId and I was looking for the SQL equivalent of WHERE user_id IN (42, 105, 302) so bars entities will now only have users whose id’s are 42, 105 or 302.
1 | // { 42, 105, 302 } |