C# LINQ

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 IEnumerable whose elements are the result of invoking the transform function on each element of source. So the below will return an IEnumerable<int> containing the Id's.
1
2
3
var foos = _fooRepository
.SelectList()
.Select(x => x.Id);

Where

Filters a sequence of values based on a predicate.

  • Returns IEnumerable that contains elements from the input sequence that satisfy the condition.
1
2
3
4
var foos = _fooRepository
.SelectList()
.Where(x => x.MemberDate >= startDate)
.Where(x => x.MemberDate < endDate);

GroupBy

Groups the elements of a sequence according to a specified key selector function.

  • Returns IEnumerable<IGrouping<TKey, TSource>>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var fooGroupsOfMemberA = _fooRepository
.SelectList()
.Where(x => x.MemberDate >= startDate)
.Where(x => x.MemberDate < endDate)
.GroupBy(grp => grp.MemberA);

/* The data would the look like:
{
{
key: 55 ~ this is `MemberA`
elements:
{
[0] an element from SelectList,
[1] an element from SelectList
},
key: 105 ~ this is `MemberA`
elements:
{
[0] an element from SelectList,
[1] an element from SelectList,
[2] an element from SelectList,
[3] an element from SelectList,
}
} */

Contains

Determines whether a sequence contains a specified element by using the default equality comparer.

  • Returns true if 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
2
3
4
5
6
7
8
// { 42, 105, 302 }
var userIds = _userRepository
.SelectList()
.Select(u => u.Id);

var bars = _fooRepository
.SelectList()
.Where(b => userIds.Contains(b.UserId));

References