【问题标题】:Convert dictionary of any type to IEnumerable collection将任何类型的字典转换为 IEnumerable 集合
【发布时间】:2011-11-09 05:41:14
【问题描述】:

我编写了一些代码来将任何IEnumerable 集合输出到文件,但不能将字典传递给它。我现在正在尝试将字典(可能是 intintintstring 或任何其他组合)转换为数组,以便我可以这样做。当我尝试将其传递给需要IEnumerable 的方法时,下面的代码表示错误。

泛型是我没有做太多的事情,所以也许我做错了什么。

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)

【问题讨论】:

  • 将字典传递给这个方法有什么问题? Dictionary 类实现 IEnumerable >
  • 感谢 Makkam - 我也有同样的想法(尽管尝试过 Dictionary 而不是 KeyValuePair)。你说的对!如果您想将此作为答案,我会打勾:)

标签: c# generics type-conversion


【解决方案1】:

这实际上取决于您要做什么:当您阅读时:Why do C# Multidimensional arrays not implement 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
}

【讨论】:

    【解决方案2】:
    TypedListToFile<string[,]>(myArray, FilePath); 
    

    myArray的类型不是IEnumerable&lt;string[,]&gt;,所以myArray不能作为这个方法的第一个参数。

    【讨论】:

    • 是的,这是个问题。 Makkam 正确地指出,如果我使用 KeyValuePair,我实际上可以直接使用我的原始方法直接使用字典,这很棒。感谢您的回答大卫。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多