将任何类型的字典转换为IEnumerable集合

本文关键字:IEnumerable 集合 转换 字典 任何 类型 | 更新日期: 2023-09-27 18:14:07

我已经编写了一些代码来将任何IEnumerable集合输出到文件中,但无法将字典传递给它。我现在正在尝试将字典(可能是intintintstring或任何其他组合(转换为数组,以便可以执行此操作。下面的代码指示当我试图将它传递给需要IEnumerable的方法时出现错误。

Generics是我做得不多的东西,所以也许我在这些方面做错了什么。

public static bool DictionaryToFile<T, U>(Dictionary<T, U> TheDictionary, string FilePath)
{
    long count = 0;
    string[,] myArray = new string[2,TheDictionary.Count];
    foreach (var current in TheDictionary)
    {
        myArray[0, count] = current.Key.ToString();
        myArray[1, count] = current.Value.ToString();
    }
    // error appears here
    TypedListToFile<string[,]>(myArray, FilePath);
    return true;
}

我打电话给的另一个:

public static bool TypedListToFile<T>(IEnumerable<T> TypedList, string FilePath)

将任何类型的字典转换为IEnumerable集合

这实际上取决于你想做什么:当你读到:为什么C#多维数组不实现IEnumerable<T>?您将看到多维数组没有实现IEnumerable,因此您必须首先转换它。然而,您的代码没有意义。我想你需要在循环中增加计数?

现在关于解决方案:您可以模拟VB行为,通过在其上应用linq查询,可以自动将多维数组转换为可枚举数组。例如:

var arrayEnumerable = from entry in myArray select entry;
// and some proof that this works:
foreach (string entry in arrayEnumerable)
{
    // this will succesfully loop your array from left to right and top to bottom
}
TypedListToFile<string[,]>(myArray, FilePath); 

myArray的类型不是IEnumerable<string[,]>,因此myArray不能是此方法的第一个参数。