ペアになった文字列の (同じ長さの) リストがあり、それらを「ソース」と「ターゲット」と呼びます。1 つのソースが複数のターゲットにマップされる場合があります。LINQ を使用して、これをルックアップ テーブル (ソースをターゲットのリストにマッピング) に変換できますか? これを行う 1 つの (長ったらしい) 方法は次のとおりです。
// There may be multiple targets corresponding to each source
// as in the following example lists.
// NB. Lists are guaranteed same length
List<string> sourceNames = new List<string>() { "A", "B", "C", "A", "B", "C" };
List<string> targetNames = new List<string>() { "Z", "Y", "X", "W", "V", "U" };
// Use extension methods to make list of unique source names
List<string> uniqueSourceNames = sourceNames.Distinct().ToList<string>();
// For each unique source, make a list of the corresponding targets
Dictionary<string, List<string>> nameLookup = new Dictionary<string, List<string>>();
foreach (string sourceName in uniqueSourceNames)
{
List<string> targetsForSource = new List<string>();
for (int index = 0; index < sourceNames.Count; index++)
{
if (sourceNames[index] == sourceName)
targetsForSource.Add(targetNames[index]);
}
nameLookup.Add(sourceName, targetsForSource);
}
// Can now use the nameLookup dictionary to map a source name to a list of target names
// e.g. this returns "Z", "W"
List<string> targets = nameLookup["A"];
LINQ を使用してこれをより効率的に行う方法はありますか?