Linq Join on Like%

One of the recent requirements I came across recently needed what looks like a Join on a ‘Like%’. Let me cite an example to demonstrate the requirement.
Consider the Collections below.

Master Collection

ID Name
1 Jia Anu
2 Sreena Anu
3 Anu Viswan

Child Collection

ID First Name Age
1 Jia 2
3 Sreena 34
5 Anu 35

I would like to Join on Master.Name and Child.FirstName where Child.FirstName StartsWith Master.Name. The expected output is as follows.

Name FirstName Age
Jia Anu Jia 2
Sreena Anu Sreena 34
Anu Viswan Anu 35

Let’s begin by defining the input collections.

var master = new List<Master>
new Master{Id=1,Name="Jia Anu"},
new Master{Id=2,Name="Sreena Anu"},
new Master{Id=3,Name="Anu Viswan"}

var child = new List<Child>
new Child{Id=1,FirstName="Jia",Age=2},
new Child{Id=2,FirstName="Sreena",Age=34},
new Child{Id=3,FirstName="Anu",Age=35}

Where Master and Child is defined as

public class Master
public int Id {get;set;}
public string Name {get;set;}

public class Child
public int Id{get;set;}
public string FirstName {get;set;}
public int Age {get;set;}

The default Join uses Equality as Comparer, and is not useful for us in this scenario. The solution lies in a little known overload of Group, which allows to provide our own customer Comparer. Let’s define our Custom Comparer.

class StartsWithEqualityComparer: IEqualityComparer<string>
public bool Equals(string right, string left)
return left.StartsWith(right);
public int GetHashCode(string obj) { return 0; }

Now, we can use our StartsWithEqualityComparer.

var result = master.Join(child,
(m,c)=> new
Name = m.Name,FirstName = c.FirstName,Age = c.Age
},new StartsWithEqualityComparer());

That’s it, we have our GroupBy with Like%.

Linq Recipes : IsIncreasing/IsDecreasing & IsAlternating

LINQ, ever since its introduction has turned out to be one of the favorite tools for .Net Developers. The post focus on couple of quick recipes for common scenarios.

Scenario 001
You have a collection of objects and you would like verify if the collection is sorted in increasing/decreasing order.


We could always sort the collection and compare with the original version, however, if you really want to stick to a LINQ based solution, following extension methods is one approach.

public static bool IsIncreasing<TSource>(this IEnumerable<TSource> data) 
   return data.Zip(data.Skip(1),(first, second) => Comparer.Default.Compare(first,second) < 0).All(b => b);

public static bool IsDecreasing<TSource>(this IEnumerable<TSource> data)
   return data.Zip(data.Skip(1),(first, second) => Comparer.Default.Compare(first,second) > 0).All(b => b);


void Main()
       var itemSet1 = new[] {1,3,4,5,6};
       var itemSet2 = new[] {5,4,3,2,1};
       Console.WriteLine($"Is {nameof(itemSet1)} increasing ? {itemSet1.IsIncreasing()}" );
       Console.WriteLine($"Is {nameof(itemSet1)} decreasing ? {itemSet1.IsDecreasing()}" );
       Console.WriteLine($"Is {nameof(itemSet2)} increasing ? {itemSet1.IsIncreasing()}" );
       Console.WriteLine($"Is {nameof(itemSet2)} decreasing ? {itemSet1.IsDecreasing()}" );


Is itemSet1 increasing ? True
Is itemSet1 decreasing ? False
Is itemSet2 increasing ? True
Is itemSet2 decreasing ? False

Scenario 002:

Consider you have a Collection ‘A’. You want to ensure that each element in the series vary in an alternating way, that is, for each element in A, A[i] < A[i+1] > A[i+2] or A[i] > A[i+1] < A[+2]. For example, for the collection {1,3,2,4,3,5} follows the pattern.

Once again we will write the solution as an extension method. Well, that’s easier to ‘reuse’ right.

public static bool IsAlternating<TSource>(this IEnumerable<TSource> dataList)
       return VerifyIfAlternating(dataList.ToList(),true) || VerifyIfAlternating(dataList.ToList(),false);

private static bool VerifyIfAlternating<TSource>(IList<TSource> data,bool toggle)
return data.Zip(data.Skip(1), (first, second) =>
                                                toggle = !toggle;
                                                return Comparer.Default.Compare(first,second) > 0 == toggle;


void Main()
       var itemSet3 = new[] {1,4,1,4,1};
       var itemSet4 = new[] {2,4,3,2,1};

       Console.WriteLine($"Is {nameof(itemSet3)} alternating ? {itemSet3.IsAlternating()}" );
       Console.WriteLine($"Is {nameof(itemSet4)} alternating ? {itemSet4.IsAlternating()}" );



Is itemSet3 alternating ? True
Is itemSet4 alternating ? False

That’s it for now. This is one series I would like to continue.

Linq : Significance of AsEnumerable

While LINQ provides a big umbrella to query in-memory as well as remote collections alike (part of the benefit is having a standard vocabulary to query any collection), there are subtle differences, which rises from the way the two classes of Linq queries work.

A Linq query over in-memory collections usually work over the IEnumerable extensions, while the queries over LINQ to SQL work over the IQueryable extensions. This is a subtle difference, considering the IQueryable inherits from IEnumerable, but the consequences can strike you if you are not expecting them.

IQuerable approach (remote query) translates the entire query to the corresponding Database Query and execute it over in the Server.

However, this means one needs to be aware that this approach has its limitations set to the Database Server capabilities, for example, Linq To Sql, is to restricted to the capabilities of the concerned Database Server.

Consider the following example. The following code attempts to read data from Exam table, where the Description Field contains a Date string. For making our life easier, we are using a RegEx.
Regex regex = new Regex(@"([01]?[0-9]|2[0-3]):[0-5][0-9]");
var output = Exams.Take (100).Where(x=> regex.IsMatch(x.Description));

However, this would result in an error as Sql doesn’t recognize regular expression, which means, Linq wouldn’t be able to convert the statement to an equivalent Sql Query.

This is where the IEnumerable.AsEnumerable method comes into picture. Let’s examine the source of the extension method in Referencesource.

  public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source)
   return source;

The method as such, if you were to look up in reference source, might be doing very less, but its significance in the scheme of things is no less important. What it does is that it converts an IQueryable to IEnumerable and there by splits the Linq statement into 2, one that executes on the Server and other, as local collection.

For example, to fix our code above, we would need to change the statement as following.

var output = Exams.Take (100).AsEnumerable().Where(x=> regex.IsMatch(x.Description));

This would split our query into two. The first part would query the Database to fetch 100 rows from Exam table. The second part would then query the resulting collection locally using the Regex expression.

Although the differences are pretty evident once you use it, it is pretty useful to visit the backing classes to understand why it behaves so.