C# Dictionary to .csv - c#

I have C# Dictionary and I want create a .csv file from it.
For example I have this dictionary:
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("0", "0.15646E3");
data.Add("1", "0.45655E2");
data.Add("2", "0.46466E1");
data.Add("3", "0.45615E0");
And I wanna this .csv file output:
0;0.15646E3;
1;0.45655E2;
2;0.46466E1;
3;0.45615E0;
How can I do this?

Maybe the easiest:
String csv = String.Join(
Environment.NewLine,
data.Select(d => $"{d.Key};{d.Value};")
);
System.IO.File.WriteAllText(pathToCsv, csv);
You'll need to add using LINQ and use at least .NET 3.5

Try the following
using (var writer = new StreamWriter(#"the\path\to\my.csv")) {
foreach (var pair in data) {
writer.WriteLine("{0};{1};", pair.Key, pair.Value);
}
}
Note: This will fail to work if the key or value elements can contain a ;. If so you will need to add an escaping mechanism to handle that

File.WriteAllLines(#"pathtocsv.csv", data.Select(x => x.Key + ";" + x.Value + ";")));

My dictionary was similar to the one in the question posed above (by user1387150) except the VALUE part was an array (of doubles, i.e.double[]).
Adjusting Jared's solution above, allows a Dictionary<string, double[]> to be written to csv as follows:
using (var writer = new StreamWriter(#"C:\path\test.csv"))
{
foreach (var pair in data)
{
writer.WriteLine("{0},{1};", pair.Key, String.Join(",", pair.Value.Select(x => x.ToString()).ToArray()));
}
}

Related

check if string contains dictionary keys and replace the matching subtring with Values from dictionary

I am parsing a template file which will contain certain keys that I need to map values to. Take a line from the file for example:
Field InspectionStationID 3 {"PVA TePla #WSM#", "sw#data.tool_context.TOOL_SOFTWARE_VERSION#", "#data.context.TOOL_ENTITY#"}
I need to replace the string within the # symbols with values from a dictionary.
So there can be multiple keys from the dictionary. However, not all strings inside the # are in the dictionary so for those, I will have to replace them with empty string.
I cant seem to find a way to do this. And yes I have looked at this solution:
check if string contains dictionary Key -> remove key and add value
For now what I have is this (where I read from the template file line by line and then write to a different file):
string line = string.Empty;
var dict = new Dictionary<string, string>() {
{ "data.tool_context.TOOL_SOFTWARE_VERSION", "sw0.2.002" },
{"data.context.TOOL_ENTITY", "WSM102" }
};
StringBuilder inputText = new StringBuilder();
StreamWriter writeKlarf = new StreamWriter(klarfOutputNameActual);
using (StreamReader sr = new StreamReader(WSMTemplatePath))
{
while((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
if (line.Contains("#"))
{
}
else
{
writeKlarf.WriteLine(line)
}
}
}
writeKlarf.Close();
THe idea is that for each line, replace the string within the # and the # with match values from the dictionary if the #string# is inside the dictionary. How can I do this?
Sample Output Given the line above:
Field InspectionStationID 3 {"PVA TePla", "sw0.2.002", "WSM102"}
Here because #WSM# is not the dictionary, it is replaced with empty string
One more thing, this logic only applies to the first qurter of the file. The rest of the file will have other data that will need to be entered via another logic so I am not sure if it makes sense to read the whole file in into memory just for the header section?
Here's a quick example that I wrote for you, hopefully this is what you're asking for.
This will let you have a <string, string> Dictionary, check for the Key inside of a delimiter, and if the text inside of the delimiter matches the Dictionary key, it will replace the text. It won't edit any of the inputted strings that don't have any matches.
If you want to delete the unmatched value instead of leaving it alone, replace the kvp.Value in the line.Replace() with String.Empty
var dict = new Dictionary<string, string>() {
{ "test", "cool test" }
};
string line = "#test# is now replaced.";
foreach (var kvp in dict)
{
string split = line.Split('#')[1];
if (split == kvp.Key)
{
line = line.Replace($"#{split}#", kvp.Value);
}
Console.WriteLine(line);
}
Console.ReadLine();
If you had a list of tuple that were the find and replace, you can read the file, replace each, and then rewrite the file
var frs = new List<(string F, string R)>(){
("#data.tool_context.TOOL_SOFTWARE_VERSION#", "sw0.2.002"),
("#otherfield#", "replacement here")
};
var i = File.ReadAllText("path");
frs.ForEach(fr => i = i.Replace(fr.F,fr.R));
File.WriteAllText("path2", i);
The choice to use a list vs dictionary is fairly arbitrary; List has a ForEach method but it could just as easily be a foreach loop on a dictionary. I included the ## in the find string because I got the impression the output is not supposed to contain ##..
This version leaves alone any template parameters that aren't available
You can try matching #...# keys with a help of regular expressions:
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
...
static string MyReplace(string value, IDictionary<string, string> subs) => Regex
.Replace(value, "#[^#]*#", match => subs.TryGetValue(
match.Value.Substring(1, match.Value.Length - 2), out var item) ? item : "");
then you can apply it to the file: we read file's lines, process them with a help of Linq and write them into another file.
var dict = new Dictionary<string, string>() {
{"data.tool_context.TOOL_SOFTWARE_VERSION", "sw0.2.002" },
{"data.context.TOOL_ENTITY", "WSM102" },
};
File.WriteAllLines(klarfOutputNameActual, File
.ReadLines(WSMTemplatePath)
.Select(line => MyReplace(line, dict)));
Edit: If you want to switch off MyReplace from some line on
bool doReplace = true;
File.WriteAllLines(klarfOutputNameActual, File
.ReadLines(WSMTemplatePath)
.Select(line => {
//TODO: having line check if we want to keep replacing
if (!doReplace || SomeCondition(line)) {
doReplace = false;
return line;
}
return MyReplace(line, dict)
}));
Here SomeCondition(line) returns true whenever header ends and we should not replace #..# any more.

How do i create a c# dictionary that will read in key and values from .csv file

I have a .csv file with a list of abbreviations and their actual meaning e.g.
Laughing Out Loud, LOL
I need to be able to search for an abbreviation in a text box and replace the abbreviation with the actual words. This is what I have attempted so far to understand dictionaries but cannot work out how to read in values from the file.
Dictionary<string, string> Abbreviations = new Dictionary<string, string>();
Abbreviations.Add("Laughing Out Loud", "lol");
foreach (KeyValuePair<string, string> abbrev in Abbreviations)
{
txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
}
You can try this LINQ solution the GroupBy is to handle the case where a key is in a file multiple times.
Dictionary<string, string[]> result =
File.ReadLines("test.csv")
.Select(line => line.Split(','))
.GroupBy(arr => arr[0])
.ToDictionary(gr => gr.Key,
gr => gr.Select(s => s[1]).ToArray());
To check if the abbreviation in the TextBox exists in the Dictionary:
foreach (KeyValuePair<string, string[]> abbrev in result)
{
if (txtinput.Text == abbrev.Value)
{
txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
}
}
You can start by creating a Stream Reader for your file, then looping for all your values in the CSV and add them to the dictionary.
static void Main(string[] args)
{
var csv_reader = new StreamReader(File.OpenRead(#"your_file_path"));
//declare your dictionary somewhere outside the loop.
while (!csv_reader.EndOfStream)
{
//read the line and split if you need to with .split('')
var line = reader.ReadLine();
//Add to the dictionary here
}
//Call another method for your search and replace.
SearchAndReplace(your_input)
}
Then have the implementation of that method, search if the input exists in the dictionary and if it does replace it.
You could use LINQ to put the values of the csv into your dictionary, if that's easier for you.
I'm going to assume that your input file may have commas in the actual text, and not just separating the two fields.
Now, if that were the case, then the standard CSV file format for format the file like this:
Laughing Out Loud,LOL
"I Came, I Saw, I Conquered",ICISIC
However, from your example you have a space before the "LOL", so it doesn't appear that you're using standard CSV.
So I'll work on this input:
Laughing Out Loud, LOL
"I Came, I Saw, I Conquered",ICISIC
"to, too, or two", 2
because,B/C
For this input then this code produces a dictionary:
var dictionary =
(
from line in File.ReadAllLines("FILE.CSV")
let lastComma = line.LastIndexOf(',')
let abbreviation = line.Substring(lastComma + 1).Trim()
let actualRaw = line.Substring(0, lastComma).Trim()
let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
? actualRaw.Substring(1, actualRaw.Length - 2)
: actualRaw
select new { abbreviation, actual }
).ToDictionary(x => x.abbreviation, x => x.actual);
You can go one better than this though. It's quite possible to create a "super function" that will do all of the replaces in one go for you.
Try this:
var translate =
(
from line in File.ReadAllLines("FILE.CSV")
let lastComma = line.LastIndexOf(',')
let abbreviation = line.Substring(lastComma + 1).Trim()
let actualRaw = line.Substring(0, lastComma).Trim()
let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
? actualRaw.Substring(1, actualRaw.Length - 2)
: actualRaw
select (Func<string, string>)(x => x.Replace(abbreviation, actual))
).Aggregate((f1, f2) => x => f2(f1(x)));
Then I can do this:
Console.WriteLine(translate("It was me 2 B/C ICISIC, LOL!"));
I get this result:
It was me to, too, or two because I Came, I Saw, I Conquered, Laughing Out Loud!

How to join values from dictionary?

I have dictionary code as follows:
int entry=0;
string[] numbers ={"123","123","123","456","123"};
Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
foreach (string number in numbers)
{
if (dictionary.ContainsKey("ABC"))
{
}
else if (!dictionary.ContainsKey("ABC") && entry==0)
{
dictionary.Add("ABC", new List<string>());
dictionary["ABC"].Add(number);
entry = 1;
}
else if (!dictionary.ContainsKey("ABC") && entry == 1)
{
dictionary["ABC"].Add(number);
}
}
foreach(KeyValuePair<string,string> kvp in dictionary)
{
Console.WriteLine("Key={0},Value = {1}", kvp.Key,kvp.Value);
}
Console.ReadKey();
I want output like as follows Key="ABC",Value="123,456" i.e. I need to print all the dictionary values only once without repeat. In above string array 123 came 4 times.But I want to print that only one time and need 456 also and also joint that values with comma(",").So I need output like Key="ABC",Value="123,456". Please share your ideas. Thanks in advance.
I need to print all the dictionary values only once without repeat.
Use Distinct method.
joint that values with comma(",")
Use String.Join method.
foreach(var kvp in dictionary)
{
Console.WriteLine("Key={0},Value = {1}",
kvp.Key,
String.Join(", " kvp.Value.Distinct())
);
}
You can try like this:
foreach(var value in dictionary.Values.Distinct())
{
names = String.Join(", ", value);
}
The following for loop variable is incorrect, I think:
foreach(KeyValuePair<string,string> kvp in dictionary)
{
Console.WriteLine("Key={0},Value = {1}", kvp.Key,kvp.Value);
}
It should read: then note the difference in the writeline
foreach(KeyValuePair<string,List<string>> kvp in dictionary)
{
Console.WriteLine("Key={0},Value = {1}", kvp.Key,string.Join(",", kvp.Value.ToArray()));
}
You can use this simple linq to flatten and join all your dictionary contents:
var result = string.Join(" - ", dic.Select(kvp => string.Format("Key={0}, Values={1}", kvp.Key, string.Join(", ",kvp.Value.Distinct()))));
Instead of using this array :
string[] numbers = {"123","123","123","456","123"};
Add another array as :
string[] uniqueNumbers = numbers.Distinct().ToArray();
and now use this array with unique values to add to the dictionary.

Simple way to read and write name value text file

I have some class with lots of fields;
public class CrowdedHouse
{
public int value1;
public float value2;
public Guid value3;
public string Value4;
// some more fields below
}
My classmust be (de)serialized into simple Windows text file in the following format
NAME1=VALUE1
NAME2=VALUE2
What is the most convinient way to do that in .NET? This is a text file and all the values must be fist converted to string. Let's assume I have already converted all data to strings.
UPDATE One option would be pinvoke WritePrivateProfileString/WritePrivateProfileString
but these are using the required "[Section]" field that I don't need to use.
EDIT: If you have already converted each data value to strings, simply use the method below to serialize it after making a Dictionary of these values:
var dict = new Dictionary<string, string>
{
{ "value1", "value1value" },
{ "value2", "value2value" },
// etc
}
or use dict.Add(string key, string value).
To read the data, simply split each line around the = and store the results as a Dictionary<string, string>:
string[] lines = File.ReadAllLines("file.ext");
var dict = lines.Select(l => l.Split('=')).ToDictionary(a => a[0], a => a[1]);
To convert a dictionary to the file, use:
string[] lines = dict.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray();
File.WriteAllLines(lines);
Note that your NAMEs and VALUEs cannot contain =.
Writing is easy:
// untested
using (var file = System.IO.File.CreateText("data.txt"))
{
foreach(var item in data)
file.WriteLine("{0}={1}", item.Key, item.Value);
}
And for reading it back:
// untested
using (var file = System.IO.File.OpenText("data.txt"))
{
string line;
while ((file.ReadLine()) != null)
{
string[] parts = line.Split('=');
string key = parts[0];
string value = parts[1];
// use it
}
}
But probably the best answer is : Use XML.
Minor improvement of Captain Comic answer:
To enable = in values: (will split only once)
var dict = lines.Select(l => l.Split(new[]{'='},2)).ToDictionary(a => a[0], a => a[1]);

Best way to read rapidshare API response?

I've started working with the rapidshare.com API. I'm just wondering what is the best way to read the reply from and API call.
To be honest I think the API is all over the place. Some replies are comma delimited which is fine. I'm having with problems with the account info response. This is not comma delimited and the fields may not always be in the same order.
Here is a sample response:
accountid=123456 type=prem servertime=1260968445 addtime=1230841165 validuntil=1262377165 username=DOWNLOADER directstart=1 protectfiles=0 rsantihack=0 plustrafficmode=0 mirrors= jsconfig=1 email=take#hike.com lots=0 fpoints=12071 ppoints=10 curfiles=150 curspace=800426795 bodkb=5000000 premkbleft=23394289 ppointrate=93
I'm thinking that regex is the way to go here. Here is my expression that seems to cath all responses that contain values:
(accountid|type|servertime|addtime|validuntil|username|directstart|protectfiles|rsantihack|plustrafficmode|mirrors|jsconfig|email|lots|fpoints|ppoints|curfiles|curspace|bodkb|premkbleft|ppointrate|refstring|cookie)\=[\w._#]+
If the order of data is to be considered random then how do I determine which value is which?
I'm just curious as to how everybody else is working with this.
Thanks,
Conor
i assume c#.
string[] s = #"accountid=123456 type=prem servertime=1260968445 addtime=1230841165 validuntil=1262377165 username=DOWNLOADER directstart=1 protectfiles=0 rsantihack=0 plustrafficmode=0 mirrors= jsconfig=1 email=take#hike.com lots=0 fpoints=12071 ppoints=10 curfiles=150 curspace=800426795 bodkb=5000000 premkbleft=23394289 ppointrate=93".Split(" ");
var params = new Dictionary<string, string>();
foreach(var l in s)
{
var tmp = l.Split("=");
params[tmp[0]] = params[tmp[1]];
}
(it may contain bugs.. but the idea is obvious?)
You probably want to split this up into a Dictionary object of some kind, so that you can access the value by a key.
Here's an example of a C# console application that works with .NET 3.5:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace SO
{
class Program
{
static void Main(string[] args)
{
string input = #"accountid=123456 type=prem servertime=1260968445";
string pattern = #"(?<Key>[^ =]+)(?:\=)(?<Value>[^ ]+)(?=\ ?)";
Dictionary<string, string> fields =
(from Match m in Regex.Matches(input, pattern)
select new
{
key = m.Groups["Key"].Value,
value = m.Groups["Value"].Value
}
).ToDictionary(p => p.key, p => p.value);
//iterate over all fields
foreach (KeyValuePair<string, string> field in fields)
{
Console.WriteLine(
string.Format("{0} : {1}", field.Key, field.Value)
);
}
//get value from a key
Console.WriteLine(
string.Format("{0} : {1}", "type", fields["type"])
);
}
}
}
Link to another example in PHP:
How to use rapidshare API to get Account Details ?? PHP question
Here is what I have done.
It's basically just a working version the code from Yossarian.
// Command to send to API
String command = "sub=getaccountdetails_v1&type=prem&login="+Globals.username+"&password="+Globals.password;
// This will return the response from rapidshare API request.
// It just performs # webrequest and returs the raw text/html. It's only a few lines. Sorry I haven't included it here.
String input = executeRequest(command);
input = input.Trim();
string[] s = input.Split('\n');
Dictionary<string,string> terms = new Dictionary<string, string>();
foreach(var l in s)
{
String[] tmp = l.Split('=');
terms.Add(tmp[0], tmp[1]);
}
foreach (KeyValuePair<String, String> term in terms)
{
txtOutput.Text += term.Key + " :: " + term.Value+"\n";
}
Thanks for your help guys.

Categories

Resources