Search code examples
c#linqfunctional-programming

How do I return a list of all matches to a dictionary lookup in C# functional/linq?


Basically attempting to

  • input a list of characters.
  • cross reference each character against a dictionary of char>string connections.
  • output a list of strings.

In normal C# I had it working similar to this:

foreach(char c in wholeString)
   if(dictionary.containskey(c))
      stringArray.Add(dictionary[c]);

return stringArray;

My failed attempt in C# functional-style or linq is this:

string inputString = "//comment";

Dictionary<char, string> crossRefDict;
   crossRefDict.Add('/', "DIVIDE");
   crossRefDict.Add('a', "ALPHA");
   crossRefDict.Add('b', "ALPHA");

Func<Dictionary<char,string>, IEnumerable<char>, IEnumerable<string>> returnCharRefs
= (dictionary, characters) => characters.Select(x => dictionary[characters]);

IEnumerable<char> inputCharacters = inputString.Select(x => x);

IEnumerable<string> characterReferences = returnCharRefs(crossRefDict, inputCharacters);

return characterReferences;

It keeps returning one result, or null results whenever the dictionary comparison hits a non-existent key. This should probably be simple, but I'm struggling.


Solution

  • You can use query syntax:

    return from c in inputString
           where dictionary.ContainsKey(c)
           select dictionary[c];
    

    or LINQ:

    return inputString
        .Where(dictionary.ContainsKey)
        .Select(c => dictionary[c]);