// Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace WhereSelectDemo
{
class Branch
{
public Guid CompanyId { get; set; }
public int BranchCode { get; set; }
// (you could add more props if needed)
}
class Program
{
static void Main()
{
try
{
const int NumItems = 200_000; // adjust if your IDE/machine can't handle this (try 200_000)
Console.WriteLine($"Creating {NumItems:N0} Branch items...");
var targetCompanyId = Guid.NewGuid();
var otherCompanyId = Guid.NewGuid();
// Create list with ~25% matches to targetCompanyId
var branches = new List<Branch>(NumItems);
for (int i = 0; i < NumItems; i++)
{
branches.Add(new Branch
{
CompanyId = (i % 4 == 0) ? targetCompanyId : otherCompanyId, // ~25% matches
BranchCode = i % 1000
});
}
Console.WriteLine($"Target CompanyId: {targetCompanyId}");
Console.WriteLine("Running Where -> Select ...");
var sw = Stopwatch.StartNew();
long hitCount1 = 0;
// Filter first, then project - selector runs only for filtered items
var result1 = branches
.Where(b =>
{
hitCount1++; // counting the predicate calls
return b.CompanyId == targetCompanyId;
})
.Select(b =>
{
hitCount1++; // counting the selector calls (only for matching items)
return new { b.CompanyId, b.BranchCode };
})
.ToArray(); // force evaluation
sw.Stop();
Console.WriteLine($"Where -> Select: {sw.ElapsedMilliseconds} ms, hitCount = {hitCount1:N0}, result count = {result1.Length:N0}");
// ---- second experiment ----
Console.WriteLine("Running Select -> Where ...");
sw.Restart();
long hitCount2 = 0;
// Project first, then filter - projector runs for all items, then predicate runs for all projected items
var result2 = branches
.Select(b =>
{
hitCount2++; // projector called for every element
return new { b.CompanyId, b.BranchCode };
})
.Where(x =>
{
hitCount2++; // predicate called for every element of the projection
return x.CompanyId == targetCompanyId;
})
.ToArray(); // force evaluation
sw.Stop();
Console.WriteLine($"Select -> Where: {sw.ElapsedMilliseconds} ms, hitCount = {hitCount2:N0}, result count = {result2.Length:N0}");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
Console.WriteLine("Done. Press any key to exit.");
Console.ReadKey();
}
}
}