将任何类型的字典转换为IEnumerable集合 [英] Convert dictionary of any type to IEnumerable collection

查看:162
本文介绍了将任何类型的字典转换为IEnumerable集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've written some code to output any IEnumerable collection to a file, but can't pass dictionaries to it. I'm now trying to convert the dictionary (which might be int, int or int, string or any other combination) into an array so I can do this. The code below indicates an error when I try to pass it to the method requiring the IEnumerable.

泛型是我没有做太多的事情,所以也许我已经完成了
$ b

Generics are something I haven't done much with so perhaps I've done something wrong with those.


        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;
    }


//另一个我是调用:

// The other one I'm calling:

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

    {


推荐答案

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

It really depends on what you are trying to do: when you read: Why do C# Multidimensional arrays not implement IEnumerable<T>? You'll see that a multidimensional array doesn't implement IEnumerable, so you have to convert it first. Yet, your code doesn't make sense. I assume you need to increment count in your loop?

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

Now as for solutions: you can simulate VB behaviour which automatically converts multi-dimensional arrays into enumerables by applying a linq query over it. like:

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
}

这篇关于将任何类型的字典转换为IEnumerable集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆