Search code examples
c#linqienumerabledenormalization

Linq expression to join a list and a dictionary


I have a list of part numbers:

var parts = new List<string> {"part1", "part2", "part3"};

I also have a dictionary of quantities for these part numbers:

var quantities = new Dictionary<string, int> {{"part1", 45}, {"part3", 25}};

Given a delimiter of |, I need to arrange these values in a flat file like so:

SalesRep|part1|part2|part3
Mr. Foo|45||25

What I'd like to do is define a string that no matter what values are in parts and quantities, I can tack this on to the sales rep name to resemble the example above.

It seems like I should be able to do this with a string.Join() on an enumerable LINQ operation, but I can't figure out what statement will get me the IEnumerable<string> result from joining parts and quantities. It thought that would be a .Join(), but the signature doesn't seem right. Can someone enlighten me?


Solution

  •  var parts = new List<string> { "part1", "part2", "part3" };
     var quantities = new Dictionary<string, int> { { "part1", 45 }, { "part3", 25 } };
    
            var result = string.Join("|", 
                   from p in parts select quantities.ContainsKey(p) 
                            ? quantities[p].ToString() : "");