我有一些遗留代码,它们接收一个string[,]作为方法参数之一。
但是,在我的方法中,我收到了一个必须转换为string[,]才能继续的IDictionary<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表达式进行转换。这有可能吗?
发布于 2012-04-02 21:00:25
当涉及到矩形数组时,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++;
}这将避免创建额外的数组,也不会依赖于Keys和Values以相同的顺序提供它们的条目。
发布于 2012-04-02 21:04:51
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++;
});https://stackoverflow.com/questions/9976909
复制相似问题