Skip to content

Instantly share code, notes, and snippets.

@savaged
Created December 19, 2022 14:52
Show Gist options
  • Save savaged/ff50100567aa4d18f76c12f1331a0b90 to your computer and use it in GitHub Desktop.
Save savaged/ff50100567aa4d18f76c12f1331a0b90 to your computer and use it in GitHub Desktop.
Emulating SQL IN statement using Linq
var needles = new List<string> { "b", "d" };
var haystack = new Dictionary<string, object>
{
{ "a", 1 },
{ "b", 2 },
{ "c", false },
{ "d", "test" }
};
Console.WriteLine("Imperatively filtered:");
foreach (var p in FilterService.ImperativelyFiltered(needles, haystack))
{
Console.WriteLine($"{p.Value}");
}
Console.WriteLine();
Console.WriteLine("Delcaratively filtered:");
foreach (var p in FilterService.DeclarativelyFiltered(needles, haystack))
{
Console.WriteLine($"{p.Value}");
}
Console.WriteLine();
static class FilterService
{
public static IDictionary<string, object> ImperativelyFiltered(
IList<string> needles,
IDictionary<string, object> haystack)
{
var filtered = new Dictionary<string, object>();
foreach (var needle in needles)
{
if (haystack.ContainsKey(needle))
{
filtered.Add(needle, haystack[needle]);
}
}
return filtered;
}
public static IDictionary<string, object> DeclarativelyFiltered(
IList<string> needles,
IDictionary<string, object> haystack) =>
haystack.Where(p => needles.Contains(p.Key)).ToDictionary(p => p.Key, p => p.Value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment