Split multi JSON value into multi rows C# - c#

I want to split a comma separated value, coming from JSON, to rows.
This
ColA:X
ColB:["1885331","2750160","151243","151241","2750159"]
To
ColA: X X
ColB:1885331 2750160 etc.
I tried to split it through Json Deserializer, but as much as I can understand the specific string isn't a list or an array. Can I split with c# ?

Is this what you want?
row.Split(',');

This should work for you. Convert your input to a string and work through it like this.
using (var sr = File.OpenText(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var fields = line.Split(',');
var test = fields[0].Trim();
}
}
Then you can create any type of object you want after.

Related

Read specific values out of a text-file and put them in a list

I have a text-file with many lines, each line looks like this:
"string string double double" between each value is a space. I'd like to read out the first string and last double of every line and put these two values in a existing list. That is my code so far, but it doesnt really work.
private void bOpen_Click(object sender, RoutedEventArgs e)
{
bool exists = File.Exists(#"C:\Users\p2\Desktop\Liste.txt");
if (exists == true)
{
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(#"C:\Users\p2\Desktop\Liste.txt"))
{
Vgl comp = new Vgl();
comp.name = Abzahlungsdarlehenrechner.zgName;
comp.gErg = Abzahlungsdarlehenrechner.zgErg;
GlobaleDaten.VglDaten.Add(comp);
int i = 0;
string line = File.ReadLines(#"Liste.txt").Skip(0).Take(1).First();
while ((line = sr.ReadLine()) != null)
{
sb.Append((line));
listBox.Items.Add(line);
GlobaleDaten.VglDaten.Add(comp);
i++;
}
}
}
I have already read this, but it didnt help How do I read specific value[...]
You can try Linq:
var source = File
.ReadLines(#"C:\Users\p2\Desktop\Liste.txt")
.Select(line => line.Split(' '))
.Select(items => new Vgl() {
name = items[0],
gErg = double.Parse(items[3])
});
// If you want to add into existing list
GlobaleDaten.VglDaten.AddRange(source);
// If you want to create a new list
//List<Vgl> list = source.ToList();
how about
List<Vgl> Result = File.ReadLines(#"C:\Users\p2\Desktop\Liste.txt")
.Select(x => new Vgl()
{
name = x.Split(' ').First(),
gErg = decimal.Parse(x.Split(' ').Last(), NumberStyles.AllowCurrencySymbol)
})
.ToList();
I would avoid storing money within doulbe values because this could lead to rounding issues. Use decimal instead. Examples here: Is a double really unsuitable for money?
You can use:
string[] splitBySpace = line.Split(' ');
string first = splitBySpace.ElementAt(0);
decimal last = Convert.ToDecimal(splitBySpace.ElementAt(splitBySpace.Length - 1));
Edit : To Handle Currency symbol:
string[] splitBySpace = line.Split(' ');
string pattern = #"[^0-9\.\,]+";
string first = splitBySpace.ElementAt(0);
string last = (new Regex(pattern)).Split(splitBySpace.ElementAt(splitBySpace.Length - 1))
.FirstOrDefault();
decimal lastDecimal;
bool success = decimal.TryParse(last, out lastDecimal);
I agree with #Dmitry and fubo, if you are looking for alternatives, you could try this.
var source = File
.ReadLines(#"C:\Users\p2\Desktop\Liste.txt")
.Select(line =>
{
var splits = line.Split(' '));
return new Vgl()
{
name = splits[0],
gErg = double.Parse(splits[3])
};
}
use string.split using space as the delimiter on line to the string into an array with each value. Then just access the first and last array element. Of course, if you aren't absolutely certain that each line contains exactly 4 values, you may want to inspect the length of the array to ensure there are at least 4 values.
reference on using split:
https://msdn.microsoft.com/en-us/library/ms228388.aspx
Read the whole file as a string.
Split the string in a foreach loop using \r\n as a row separator. Add each row to a list of strings.
Iterate through that list and split again each record in another loop using space as field separator and put them into another list of strings.
Now you have all the four fields containig one row. Now just use First and Last methods to get the first word and the last number.

Read CSV files to two arrays c#

I have a situation that need to make two arrays from each column of csv file. As shown below, the csv file contain two columns each column has a header titled 'period' and 'acceleration'.
Period,Acceleration
0.01,0.6
0.05,0.82
0.1,1.26
0.15,1.403
0.2,1.383
I tried to use following code and then split this into two arrays. However, it did not break the numbers by comma.
string[] allLines = File.ReadAllText(#"C:\ArsScale\Tars.csv").Split(',');
static void getTwoArraysFromFile(string filein, ref double[] acc, ref double[] period)
{
string line;
List<double> p1 = new List<double>();
List<double> p2 = new List<double>();
System.IO.StreamReader file = new System.IO.StreamReader(filein);
while ((line = file.ReadLine()) != null)
try {
String[] parms = line.Trim().Split(',');
p1.Add(double.Parse(parms[1], CultureInfo.InvariantCulture));
p2.Add(double.Parse(parms[0], CultureInfo.InvariantCulture));
}
catch { }
acc = p1.ToArray();
period = p2.ToArray();
}
IEnumerable<string[]> allLines = File.ReadAllLines(#"C:\ArsScale\Tars.csv").Select(x => x.Split(','));
This will read all the lines from the text file, then split each line. The datatype will be IEnumerable of string[]. To change this to string[][], simply call .ToArray() after the Select statement.
This method is quick and simple, however it does absolutely no validation on the input. For example, the CSV spec allows for commas to be present inside of values as long as they are escaped. If you need to have validation of any kind, you need to look into a CSV parser, of which there are many.
If you need no validation, you're positive about the input, and don't care about good error handling, you can use the following:
var allLines = File.ReadAllLines(#"C:\ArsScale\Tars.csv").Select(x => x.Split(',').Select(y => double.Parse(y).ToArray())).ToArray();
This will give you double[][] as your output.
Use a StreamReader to read your csv line by line. Then split each line and add each value to a list. Finally create two arrays from your lists.
List<Double> periodList = new List<Double>();
List<Double> accelerationList = new List<Double>();
StreamReader file = new System.IO.StreamReader(#"C:\ArsScale\Tars.csv");
string line = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
string[] data = line.Split(',');
periodList.Add(Convert.ToDouble(data[0]);
accelerationList.Add(Convert.ToDouble(data[1]);
}
Double[] periodArray = periodList.ToArray();
Double[] accelerationArray = accelerationList.ToArray();
String.Split is not a robust way of parsing CSV fields, as they may contain commas within the fields etc
In any case you need to use File.ReadAllLines, not File.ReadAllText
File.ReadAllLines gives you a array of strings - 1 for each line.
You could then iterate through the array and copy to 2 other arrays for each item.
Example:
var lines = File.ReadAllLines (#"C:\ArsScale\Tars.csv");
var periods = lines.Skip(1).Select(x => x.Split(",")[0]).ToArray();
var accelerations = lines.Skip(1).Select(x => x.Split(",")[1]).ToArray();
However I'd advise a more robust method.
Have a look at this article: http://www.codeproject.com/Articles/415732/Reading-and-Writing-CSV-Files-in-Csharp

Fetch csv kind of data from text file [duplicate]

This question already has answers here:
Parsing CSV files in C#, with header
(19 answers)
Closed 1 year ago.
I am having string which gives data more like to csv format .
&stamp;field1;field2;field3;field4;&event
10:44:00.6100;0.000;0.000;0.000;0.000; 10:44:00.7100;23.2;0.230;411.2;0.000; 10:44:00.8100;0.000;0.000;1.022;0.000; 10:44:00.9100;8.000;0.000;232.3;0.000;
10:44:01.2100;0.000;0.000;0.000;0.000; 10:44:01.3100;23.2;0.230;411.2;0.000; 10:44:01.5100;0.000;0.000;1.022;0.000; 10:44:01.7100;8.000;0.000;232.3;0.000;
I want to deserialize this data.
this will give you a list of strings "split" at every ; char. you will want to trim and parse the values after. hope this helps
var stringOfData = "0:44:00.6100;0.000;0.000;0.000;0.000; 10:44:00.7100;23.2;0.230;411.2;0.000; 10:44:00.8100;0.000;0.000;1.022;0.000; 10:44:00.9100;8.000;0.000;232.3;0.000;";
List<string> parsed = new List<string>();
parsed.AddRange(stringOfData.Split(';'));
string line = String.Empty;
string[] parts = null;
using (StreamReader sr = new StreamReader(new FileStream(#"C:\yourfile.csv",
FileMode.Open)))
{
while ((line = sr.ReadLine()) != null)
{
parts = line.Split(new [] { ';' });
//Do whatever you want to do with the array of values here
}
}
As for the deserialization part of the question; you would need to specify the kind of format you would want. If you just want a collection of numbers you want to loop through, you could just add every value to a generic List.
If you want a specific format, you could create a class with fields for each of those values and populate a generic list of that class using those values.

Searching for text in a .txt

What would be the best way to search a text file that looks like this..?
efee|| Nbr| Address| Name |Phone|City|State|Zip abc
||455|gsgd |first last|gsg |fef |jk |0393 gjgj||jfj|ddg
|first last|fht |ree |hn |th ...more lines...
I started by reading in the file and all its contexts with a streamreader
I was thinking to count the "|" and grab the text between the 5th and 6th using substring but i'm not sure how to do the count of the "|". Or if someone has a better idea I'm open to it.
Tried something like this:
StreamReader file = new StreamReader(#"...");
string line;
int num=0;
while ((line = file.ReadLine()) != null)
{
for (int i = 1; i <= 6; i++)
{
if (line.Contains("|"))
{
num++;
}
}
int start = line.IndexOf("|");
int end = line.IndexOf("|");
string result = line.Substring(start, end - start - 1);
}
The text I want I beleive is always between the 5th and 6th "|"
You can do it like this:
var res = File
.ReadLines(#"FileName.txt")
.Select(line => line.Split(new[]{'|'}, StringSplitOptions.None)[5])
.ToList();
This produces a List<strings> from the file, where each string is the part of the corresponding line of the file taken from between the fifth and the sixth '|' separator.
For a delimited file you should use a parser - there is one in the Microsoft.VisualBasic.FileIO namespace - the TextFieldParser class, though you could also look at third-party libraries like the popular FileHelpers.
A simpler approach would be to use string.Split on the | character and getting the value in the corresponding index of the returned string[], however, if any of the fields are escaped and can validly contain | internally, this will fail.
You could split each line into an array:
while ((line = file.ReadLine()) != null)
{
var values = line.Split('|');
}
This should work
string txt = File.ReadAllText("file.txt");
string res = Regex.Match(txt, "\\|*?{5}(.+?)\\|", RegexOptions.Singleline).Result("$1");

Searching strings in txt file

I have a .txt file with a list of 174 different strings. Each string has an unique identifier.
For example:
123|this data is variable|
456|this data is variable|
789|so is this|
etc..
I wish to write a programe in C# that will read the .txt file and display only one of the 174 strings if I specify the ID of the string I want. This is because in the file I have all the data is variable so only the ID can be used to pull the string. So instead of ending up with the example about I get just one line.
eg just
123|this data is variable|
I seem to be able to write a programe that will pull just the ID from the .txt file and not the entire string or a program that mearly reads the whole file and displays it. But am yet to wirte on that does exactly what I need. HELP!
Well the actual string i get out from the txt file has no '|' they were just in the example. An example of the real string would be: 0111111(0010101) where the data in the brackets is variable. The brackets dont exsist in the real string either.
namespace String_reader
{
class Program
{
static void Main(string[] args)
{
String filepath = #"C:\my file name here";
string line;
if(File.Exists(filepath))
{
StreamReader file = null;
try
{
file = new StreamReader(filepath);
while ((line = file.ReadLine()) !=null)
{
string regMatch = "ID number here"; //this is where it all falls apart.
Regex.IsMatch (line, regMatch);
Console.WriteLine (line);// When program is run it just displays the whole .txt file
}
}
}
finally{
if (file !=null)
file.Close();
}
}
Console.ReadLine();
}
}
}
Use a Regex. Something along the lines of Regex.Match("|"+inputString+"|",#"\|[ ]*\d+\|(.+?)\|").Groups[1].Value
Oh, I almost forgot; you'll need to substitute the d+ for the actual index you want. Right now, that'll just get you the first one.
The "|" before and after the input string makes sure both the index and the value are enclosed in a | for all elements, including the first and last. There's ways of doing a Regex without it, but IMHO they just make your regex more complicated, and less readable.
Assuming you have path and id.
Console.WriteLine(File.ReadAllLines(path).Where(l => l.StartsWith(id + "|")).FirstOrDefault());
Use ReadLines to get a string array of lines then string split on the |
You could use Regex.Split method
FileInfo info = new FileInfo("filename.txt");
String[] lines = info.OpenText().ReadToEnd().Split(' ');
foreach(String line in lines)
{
int id = Convert.ToInt32(line.Split('|')[0]);
string text = Convert.ToInt32(line.Split('|')[1]);
}
Read the data into a string
Split the string on "|"
Read the items 2 by 2: key:value,key:value,...
Add them to a dictionary
Now you can easily find your string with dictionary[key].
first load the hole file to a string.
then try this:
string s = "123|this data is variable| 456|this data is also variable| 789|so is this|";
int index = s.IndexOf("123", 0);
string temp = s.Substring(index,s.Length-index);
string[] splitStr = temp.Split('|');
Console.WriteLine(splitStr[1]);
hope this is what you are looking for.
private static IEnumerable<string> ReadLines(string fspec)
{
using (var reader = new StreamReader(new FileStream(fspec, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
var dict = ReadLines("input.txt")
.Select(s =>
{
var split = s.Split("|".ToArray(), 2);
return new {Id = Int32.Parse(split[0]), Text = split[1]};
})
.ToDictionary(kv => kv.Id, kv => kv.Text);
Please note that with .NET 4.0 you don't need the ReadLines function, because there is ReadLines
You can now work with that as any dictionary:
Console.WriteLine(dict[12]);
Console.WriteLine(dict[999]);
No error handling here, please add your own
You can use Split method to divide the entire text into parts sepparated by '|'. Then all even elements will correspond to numbers odd elements - to strings.
StreamReader sr = new StreamReader(filename);
string text = sr.ReadToEnd();
string[] data = text.Split('|');
Then convert certain data elements to numbers and strings, i.e. int[] IDs and string[] Strs. Find the index of the given ID with idx = Array.FindIndex(IDs, ID.Equals) and the corresponding string will be Strs[idx]
List <int> IDs;
List <string> Strs;
for (int i = 0; i < data.Length - 1; i += 2)
{
IDs.Add(int.Parse(data[i]));
Strs.Add(data[i + 1]);
}
idx = Array.FindIndex(IDs, ID.Equals); // we get ID from input
answer = Strs[idx];

Categories

Resources