0

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.

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)
Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
Glinkot
  • 2,924
  • 10
  • 42
  • 67
  • 2
    What's the problem to pass dictionary to this method? Dictionary class implements IEnumerable > – default locale Nov 09 '11 at 05:49
  • 1
    Thanks Makkam - I kind of thought the same (though had tried Dictionary not KeyValuePair). You are right! If you'd like to put this as an answer I'll tick it off :) – Glinkot Nov 09 '11 at 05:55

2 Answers2

1

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?

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
}
Community
  • 1
  • 1
Polity
  • 14,734
  • 2
  • 40
  • 40
0
TypedListToFile<string[,]>(myArray, FilePath); 

The type of myArray is not IEnumerable<string[,]>, so myArray can't be the first parameter to this method.

Amy B
  • 108,202
  • 21
  • 135
  • 185
  • 1
    Yep that's an issue. Makkam has correctly pointed out that if I used KeyValuePair I can actually use the dictionary directly with my original method which is great. Thanks for your answer David. – Glinkot Nov 09 '11 at 05:56