我有成对字符串的列表(长度相等),称它们为“源”和“目标”。一个源可以映射到多个目标。我可以使用 LINQ 将其转换为查找表(将源映射到目标列表)吗?一种(冗长的)方法是:
// 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 更有效地做到这一点?