在C#中加入/合并数组

Ber*_*ius 5 .net c# linq arrays c#-3.0

我有两个或更多数组 - 一个有ID,一个或多个有字符串值.我想将这些合并到一个哈希表中,以便我可以按ID查找值.

以下函数可以完成这项工作,但更短更甜的版本(LINQ?)会很好:

Dictionary<int, string[]> MergeArrays( IEnumerable<int> idCollection,
                                       params IEnumerable<string>[] valueCollections )
{
    var dict = new Dictionary<int, string[]>();

    var idL = idCollection.Count();
    while ( idL-- > 0 )
    {
        dict[idCollection.ElementAt( idL )] = new string[valueCollections.Length];

        var vL = valueCollections.Length;
        while ( vL-- > 0 )
            dict[idCollection.ElementAt( idL )][vL] = valueCollections[vL].ElementAt( idL );
    }

    return dict;
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Jon*_*eet 3

目前,这是非常低效的 - 所有这些对 ElementAt 的调用每次都可能会遍历整个序列(只要它们需要)。(这取决于序列的实现。)

但是,我根本不确定我是否理解这段代码在做什么(使用 foreach 循环几乎肯定会使其更清晰,就像向前迭代而不是向后迭代一样。您能提供一些示例输入吗?和预期输出?

编辑:好的,我想我明白这里发生了什么;您正在有效地旋转 valueCollections。我怀疑你会想要这样的东西:

static Dictionary<int, string[]> MergeArrays(
    IEnumerable<int> idCollection,
    params IEnumerable<string>[] valueCollections)
{
    var valueCollectionArrays = valueCollections.Select
         (x => x.ToArray()).ToArray();
    var indexedIds = idCollection.Select((Id, Index) => new { Index, Id });

    return indexedIds.ToDictionary(x => Id, 
        x => valueCollectionArrays.Select(array => array[x.Index]).ToArray());
}
Run Code Online (Sandbox Code Playgroud)

虽然它非常丑陋。如果你可以让 idCollection 成为一个数组来开始,坦率地说会更容易。

编辑:好的,假设我们可以使用数组代替:

static Dictionary<int, string[]> MergeArrays(
    int[] idCollection,
    params string[][] valueCollections)
{
    var ret = new Dictionary<int, string[]>();
    for (int i=0; i < idCollection.Length; i++)
    {
         ret[idCollection[i]] = valueCollections.Select
             (array => array[i]).ToArray();
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

我已经(希望)纠正了第一个版本中的一个错误 - 我对哪些值是数组而哪些不是数组感到困惑。第二个版本没有那么明确,但我个人认为它更清晰。