Skip to content

Instantly share code, notes, and snippets.

@JaimeStill
Created July 18, 2023 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaimeStill/c4d8ef3ed1376b0f5edc7f1c8267bb95 to your computer and use it in GitHub Desktop.
Save JaimeStill/c4d8ef3ed1376b0f5edc7f1c8267bb95 to your computer and use it in GitHub Desktop.
Flatten a list within a list into a projection of objects

Project Items From a Sub-List

Initial Data Source

Dictionary<KeyValuePair<string, string>, List<string>> PropertyMap = new()
{
    { new("PACKAGE_TYPE", "PackageType"), new() },
    { new("TURNAROUND_TIME", "TurnaroundTime"), new() },
    { new("TRACKING", "Tracking"), new() }
};

Projection Target

public class PackageMetadata
{
    public int PackageId { get; set; }
    public string Key { get; set; }
    
    [NotMapped]
    public string SourceId { get; set; }
}

Populate Values

foreach (KeyValuePair<KeyValuePair<string, string>, List<string>> map in PropertyMap)
    // Get PackageIds for records that have a value associated with column 'map.Key.Key'
    map.Value.AddRange(await GetPackageIds(map.Key.Key));

Projection Method

List<PackageMetadata> FromPropertyMap() => PropertyMap
    .SelectMany(x =>
        x.Value.Select(y => new PackageMetadata
        {
            PackageId = y,
            Key = x.Key.Value,
            SourceId = $"{y}:{x.Key.Key}"
        })
    )
    .ToList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment