I have a C# Dictionary which I create by reading multiple data sources. The Dictionary contains key value pairs where the value collection of a key is a comma seperated string value.
for example:
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("cat", "2,2");
d.Add("dog", "10, A");
d.Add("llama", "A,B");
开发者_运维问答 d.Add("iguana", "-2,-3");
I want the final csv file to look like this:
cat, dog, llama, iguana
2,10,A,-2
2,A,B,-3
How do I achieve this?
It would be easier if your data structure was Dictionary, otherwise you'll need to split out the items in advance or do it multiple times in a loop. A List would work also. Depending on how you're getting the data in from your data sources should determine whether it is easier to do a String.Split() on the data coming in (e.g. it's already a delimited string), or whether each item is being added individually.
This code could be optimized (e.g. get rid of the dictionary lookups each time through the loops) and cleaned up, but should get you started, and should be fine if your data set is not too large:
static void Main(string[] args)
{
Dictionary<string, string[]> d = new Dictionary<string, string[]>();
d.Add("cat", new string[] { "2", "2" });
d.Add("dog", new string[] { "10", "A" });
d.Add("llama", new string[] { "A", "B" });
d.Add("iguana", new string[] { "-2", "-3" });
// Not clear if you care about the order - this will insure that the names are in alphabetical order.
// The order of items in a dictionary are not guarenteed to be the same as the order they were added.
var names = d.Keys.OrderBy(l => l).ToList();
// Not clear if you know the number of items that will be in the list in advance - if not, find the max size
int maxSize = d.Values.Max(a => a != null ? a.Length : 0);
Console.WriteLine(String.Join(", ", names));
for (int i = 0; i < maxSize; i++)
{
foreach (string name in names)
{
string[] value = d[name];
if ((value != null) && (i < value.Length))
{
Console.Write(value[i]);
}
if (name != names.Last())
{
Console.Write(",");
}
}
Console.WriteLine();
}
}
Will generate this output:
cat, dog, iguana, llama
2,10,-2,A
2,A,-3,B
A Dictionary used in a foreach will return a KeyValuePair ... where you can access the "Key" and "Value". For the extracting of the "value" you can use string.Split(). The rest should be relativly easy depending on what you exactly need.
[Edit] And finally you just open a text file for write, and dump the data out the way you want.
Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
d.Add("cat", new List<string> {"2", "2"});
d.Add("dog", new List<string> {"10", "A"});
d.Add("llama", new List<string>{"A","B"});
d.Add("iguana", new List<string>{"-2","-3"});
List<List<string>> values = d.Values.AsQueryable().ToList();
int count = values[0].Count;
for (int i = 0; i < count; i++)
{
for (int j = 0; j < values.Count; j++)
{
Console.Write(values[j].ElementAt(i));
}
}
Ommited checks and formatting but this does what you want.
精彩评论