2

ペアになった文字列の (同じ長さの) リストがあり、それらを「ソース」と「ターゲット」と呼びます。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 を使用してこれをより効率的に行う方法はありますか?

4

2 に答える 2

1

あなたは使用することができGroupByますToDictionary

var lookup = sourceNames
   .Select((Source, i) => new { Target = targetNames.ElementAt(i), Source})
   .GroupBy(x => x.Source)
   .ToDictionary(g => g.Key, g => g.Select(x => x.Target));

これで、すべての個別のソース文字列がIEnumerable<string>ターゲットにマップされます。

foreach (var kv in lookup)
    Console.WriteLine("{0} has destinations {1}"
        , kv.Key
        , string.Join(",", lookup[kv.Key]));

編集:これがデモです:http://ideone.com/b18H7X

于 2012-10-24T11:29:03.780 に答える
0

ZipとToLookupを使用できます。

var nameLookup = sourceNames
  .Zip(targetNames, (x, y) => new { Source = x, Target = y })
  .ToLookup(x => x.Source, x => x.Target);
于 2012-10-24T15:33:56.610 に答える