IDictionary<;字符串,字符串>;LINQ将其转换为字符串[,]

本文关键字:字符串 转换 gt lt IDictionary LINQ | 更新日期: 2023-09-27 18:29:40

我有一些遗留代码,它接收string[,]作为方法参数之一。

然而,在我的方法中,我收到了一个IDictionary<string, string>,必须将其转换为string[,]才能继续。

我已经创建了这样的代码,

var names = attachments.Keys.ToArray();
var paths = attachments.Values.ToArray();
var multipleAttachments = new string[2,attachments.Count];
for(var i = 0; i < attachments.Count; i++)
{
  multipleAttachments[0, i] = names[i];
  multipleAttachments[1, i] = paths[i];
}

我对此并不满意,我正在寻找一些方法来使用LINQ表达式进行转换。这可能吗?

IDictionary<;字符串,字符串>;LINQ将其转换为字符串[,]

LINQ在矩形数组方面不是特别好。您可以轻松创建锯齿状阵列:

// Note that this ends up "rotated" compared with the rectangular array
// in your question.
var array = attachments.Select(pair => new[] { pair.Key, pair.Value })
                       .ToArray();

但是矩形阵列没有等效的。如果使用矩形数组,您可能需要考虑创建一个扩展方法来执行转换。如果你只想在这种情况下使用它,你可能最好坚持你所拥有的。。。或者可能:

var multipleAttachments = new string[2, attachments.Count];
int index = 0;
foreach (var pair in multipleAttachments)
{
    multipleAttachments[0, index] = pair.Key;
    multipleAttachments[1, index] = pair.Value;
    index++;
}

这将避免创建额外的数组,也不会依赖于KeysValues以相同的顺序提供它们的条目。

var multipleAttachments = new string[2, attachments.Count];
            int i = 0;
            attachments.ToList().ForEach(p =>
                {
                    multipleAttachments[0, i] = p.Key;
                    multipleAttachments[1, i] = p.Value;
                    i++;
                });