Removing a parent Node from a flattened json response - c#

I have a flattened json response like this :
"data.Applicant.Age", "0"
"data.Applicant.IsInsured", "True"
i want to be able to remove data from the flattened collection using C#.
My Expected result should look like this :
"Applicant.Age","0"
"Applicant.IsInsured","True"

var input = #"""Applicant.Age"",""0""
""Applicant.IsInsured"",""True"""; // this is a string containing Environment.Newline
var lines = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
var newLines = new List<string>();
string output;
foreach (var line in lines)
{
var key = line.Split(',')[0].Trim();
var value = line.Split(',')[1].Trim();
key = key.Substring(6);
var newLine = string.Join(":", key, value);
newLines.Add(newLine);
Console.WriteLine(newLine);
}
This code converts your input, which is a string containing two lines, to output, which is a string containing two lines and each line does not have the data. part.

Related

Split String with multiple delimiters to different arrays in c#

So I have a text file copied into memory that is delimited as follows:
"425,9856\n852,9658\n"
This is a long string with some 30,000 entries in total. What I want to do is create two arrays, one for the value to the left of the comma, one for the value to the right of the comma, and then to each array respectively i want to append the next two comma delimited strings that come after the "\n".
I have tried splitting using .Split and passing two delimiting values, but it obviously just creates one array with all values sequentially. Such as:
425
9856
852
9658
When what I want is:
array1:
452
852
array2:
9856
9658
Does that make sense?
many thanks
Since you're reading from a file, why not stream the input line-by-line, rather than reading the whole lot into memory in one go?
using var reader = new StreamReader(filePath);
while (reader.ReadLine() is not null line)
{
// Each line is of the form '425,9856', so just split on the comma
var parts = line.Split(',');
firstList.Add(parts[0]);
secondList.Add(parts[1]);
}
You can just split it twice to get what you want
public static void Main()
{
var foo = "425,9856" + Environment.NewLine + "852,9658" + Environment.NewLine;
var array1 = new List<string>();
var array2 = new List<string>();
string[] lines = foo.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None);
foreach(var line in lines)
{
//Console.WriteLine("line: " + line);
var lineSplit = line.Split(',');
//Console.WriteLine("lineSplit: " + lineSplit.Length);
//lineSplit.Dump();
if(lineSplit.Length > 1)
{
array1.Add(lineSplit[0]);
array2.Add(lineSplit[1]);
}
}
Console.WriteLine("Array1: ");
array1.Dump();
Console.WriteLine("Array2: ");
array2.Dump();
}
And here's a working fiddle of it.
You can use RegEx
string row = #"425,9856\n852,9658\n";
string left = #"[^|(?<=n)]\d*(?=,)";
string right = #"(?<=,)\d*(?=\\)";
Regex rgLeft = new Regex(left);
var l = rgLeft.Matches(row).Select(p=> p.Value);
Regex rgRight = new Regex(right);
var r = rgRight.Matches(row).Select(p=> p.Value);

Merge 2 lines in .CSV file using StreamReader

I am currently trying to merge some lines in a .csv file. The file follows a specific format which is split by "," and the last element uses \n ascii code. This means the last element gets put onto a new line and i return an array with only one Element. I am looking to merge this element with the line above it.
So my line would be:
192.168.60.24, ACD_test1,86.33352, 07/12/2014 13:33:13, False, Annotated, True,"Attribute1
Attribute 2
Attribute 3"
192.168.60.24, ACD_test1,87.33352, 07/12/2014 13:33:13, False, Annotated, True
Is it possible to merge/join the new line attributes with the line above?
My code is shown below:
var reader = new StreamReader(File.OpenRead(#path));
string line1 = reader.ReadLine();
if (line1.Contains("Server, Tagname, Value, Timestamp, Questionable, Annotated, Substituted"))
{
while (!reader.EndOfStream)
{
List<string> listPointValue = new List<string>();
var line = reader.ReadLine();
var values = line.Split(',');
if (values.Count() < 2)
{
//*****Trying to Add Attribute to listPointValue.ElememtAt(0) here******
}
else
{
foreach (string value in values)
{
listPointValue.Add(value);
}
allValues.Add(listPointValue);
}
}
// allValues.RemoveAt(0);
return allValues;
}
I think you want to read the next line before you do the allValues.Add. That way you can decide whether to add the previous line to allValues (starting a new line). This gives you an idea of what I mean:
var reader = new StreamReader(File.OpenRead(#path));
string line1 = reader.ReadLine();
if (line1.Contains("Server, Tagname, Value, Timestamp, Questionable, Annotated, Substituted"))
{
List<string> listPointValue = new List<string>();
// Add first line to listPointValue
var line = reader.ReadLine();
var values = line.Split(',');
foreach (string value in values)
{
listPointValue.Add(value);
}
while (!reader.EndOfStream)
{
// Read next line
line = reader.ReadLine();
values = line.Split(',');
// If next line is a full line, add the previous line and create a new line
if (values.Count() > 1)
{
allValues.Add(listPointValue);
listPointValue = new List<string>();
}
// Add values to line
foreach (string value in values)
{
listPointValue.Add(value);
}
}
allValues.Add(listPointValue);
}

Getting Data From IEnumerable

I have text file which contains airport Codes in this format:
"AAA","","Anaa Arpt","PF","","","AAA","2","N","272"
I used a StreamReader to to read the line from file and then I add that line to string list finally I convert that list to IEnumerable type.
Can you please help me how could I get only three values from each line for example
AAA is airportCode
Anna Arpt airport name
PF is country Code
I want to get only these three values from each row.
Please find below the code.
using (StreamReader sr = new StreamReader("C:/AirCodes/RAPT.TXT"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
aircodesFromTravelPort.Add(line);
Console.WriteLine(line);
}
}
var codes = (IEnumerable<String>)aircodesFromTravelPort;
foreach (var aircode in codes)
It seems that you can try using Linq, something like that:
var codes = File
.ReadLines(#"C:/AirCodes/RAPT.TXT")
.Select(line => line.Split(','))
.Select(items => new {
// I've created a simple anonymous class,
// you'd probably want to create you own one
Code = items[0].Trim('"'), //TODO: Check numbers
Airport = items[2].Trim('"'),
Country = items[3].Trim('"')
})
.ToList();
...
foreach(var item in codes)
Console.WriteLine(item);
You'll probably want to make use of String's Split function on each line to get the values into an array.
while ((line = sr.ReadLine()) != null)
{
var values = line.Split(","); // here you have an array of strings containing the values between commas
var airportCode = values[0];
var airportName = values[2];
var airportCountry = values[3];
var airportInfo = airportCode + "," + airportName + "," + airportCountry;
aircodesFromTravelPort.Add(airportInfo );
// what you actually do with the values is up to you, I just tried to make it as close to the original as possible.
Console.WriteLine(airportInfo);
}
Hope this helps!
I like Regex with named groups:
var line = #"""AAA"","""",""Anaa Arpt"",""PF"","""","""",""AAA"",""2"",""N"",""272""";
var pattern = #"^""(?<airportCode>\w+)"",""(\w*)"",""(?<ariportName>[\w\s]+)"",""(?<cuntryCode>\w+)""";
Match match = Regex.Match(line, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string airportCode = match.Groups["airportCode"].Value;
string ariportName = match.Groups["ariportName"].Value;
string cuntryCode = match.Groups["cuntryCode"].Value;
}

C# Why do I only get partial results when parsing out a CSV or TSV file?

I am trying to get the second value from a CSV file with 100 rows. I am getting the first 42 values then it stops... no error messege, or error handling at all for that matter. I am perplexed and am on a timeline. It is also doing it for a TSV file, but giving the first 43 results. Please help and let me know if it looks strange to you.
I am using streamreader, reading each line into a string array, splitting the array and taking the second value and adding it to a list...
string path = #"C:\Users\dave\Desktop\codes\testfile.txt";
StreamReader sr = new StreamReader(path);
List<string> stkno = new List<string>();
foreach (var line in path)
{
string s = sr.ReadLine();
string[] words = s.Split(',');
stkno.Add(words[1]);
}
var message = string.Join(",", stkno.ToArray());
MessageBox.Show(message);
Your path variable is a string. That means when you foreach over it, you're getting a sequence of characters - 'C' then ':' then '\' etc. I don't think that's what you mean to do...
Here's a simpler approach using File.ReadLines:
string path = #"C:\Users\dave\Desktop\codes\testfile.txt";
List<string> stkno = (from line in File.ReadLines(path)
let words = line.Split(',')
select words[1]).ToList();
Or:
string path = #"C:\Users\dave\Desktop\codes\testfile.txt";
List<string> stkno = File.ReadLines(path)
.Select(line => line.Split(',')[1])
.ToList();
If you're using .NET 3.5 and you don't mind reading the whole file in one go, you can use File.ReadAllLines instead.
You are accidentally iterating over the number of characters in the file path instead of the number of lines in the string. This change should fix that:
string path = #"C:\Users\dave\Desktop\codes\testfile.txt";
StreamReader sr = new StreamReader(path);
List<string> stkno = new List<string>();
while (sr.Peek() >= 0)
{
string s = sr.ReadLine();
string[] words = s.Split(',');
stkno.Add(words[1]);
}
var message = string.Join(",", stkno.ToArray());
MessageBox.Show(message);
How about this:
string path = #"C:\Users\dave\Desktop\codes\testfile.txt";
var secondWords = from line in File.ReadAllLines(path)
let words = line.Split(',')
select words[1];
var message = string.Join(",", secondWords.ToArray());
I think you mean to do:
string path = #"C:\Users\dave\Desktop\codes\testfile.txt";
StreamReader sr = new StreamReader(path);
List<string> stkno = new List<string>();
string s;
while(s = sr.ReadLine() != null)
{
string[] words = s.Split(',');
stkno.Add(words[1]);
}
var message = string.Join(",", stkno.ToArray());
MessageBox.Show(message);

parsing a long string in c# and giving those values to parameters

I have this string in C# -
".... School||Abc\r\n...State||CA\r\n..."
The school and state are somewhere in the string. I need to parse the string in such a way that i get the values of School and State for my parameters
string school = abc (from String after parsing)
string state = CA (from string after parsing)
Try this:
string longStr = "School||Abc\r\nState||CA\r\n";
string[] keyValPairs = s.Split("\r\n".ToCharArray());
Dictionary<string, string> info = new Dictionary<string, string>();
foreach(string pair in keyValPairs)
{
string[] split = pair.Split("||");
//split[0] is the key, split[1] is the value
info.Add(split[0], split[1]);
}
Now you can access what you need like so:
string school = info["School"];
string state = info["State"];
Where the longStr variable is just your long string that you start out with, not neccessarily what I set it to.
Try split-ing string on new line chars and then it looks like a dictionary, with key values separated by ||. Another split on "||" should give you what you want.
Back of the envelope code
private static void ParseMyString(string longString) {
IEnumerable<string> shortStrings = longString.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(var ss in shortStrings) {
var kvp = ss.Split("||".ToCharArray());
Console.WriteLine("{0} - {1}", kvp[0], kvp[1]);
}
}
You can use the TextFieldParser class to parse this file, in particular if it is fixed width fields or has known delimiters.
It:
Provides methods and properties for parsing structured text files.
Though it lives in the Microsoft.VisualBasic.Text namespace, it is a .NET assembly and can be used in all .NET projects.
Assuming that your string just contains values separated by "||", "\r" or "\n".
string str = "School||Abc\r\n||State||CA\r\n||AA||AA";
str = str.Trim();
str = str.Replace("\r",string.Empty);
str = str.Replace("\n", string.Empty);
string[] keyValue = str.Split(new string[] { "||" }, StringSplitOptions.None);
Dictionary<string, string> KeyValDic = new Dictionary<string, string>();
for (int i = 0; i < keyValue.Length; i++,i++)
{
KeyValDic.Add(keyValue[i], keyValue[i + 1]);
}

Categories