Splitting a list<string> item and formatting it out - c#

I have a List that is being filled with something like this in a loop:
myList.Add("john,smith,50,actor");
Obviously I just wrote the pure string, they are actually some variables. Now what I want to do is to export this to a text file using Stringbuilder and StringWriter which I think I can manage it (already did similar things).
So I want my textfile to look like this:
NAME SURNAME AGE WORK
john smith 50 actor
And so on. Can you help me figure out a foreach loop for this case?

const string Format = "{0,-10} {1,-10} {2,-10} {3,-10}";
var myList = new List<string>();
myList.Add("john,smithhh,50,actor");
myList.Add("a,b,c,d");
var res = myList.Select(i => i.Split(','));
Console.WriteLine(Format, "NAME", "SURNAME", "AGE", "WORK");
foreach (var line in res)
{
Console.WriteLine(Format, line[0], line[1], line[2], line[3]);
}
Output:
NAME SURNAME AGE WORK
john smithhh 50 actor
a b c d

Here is how can create a text file our or your List<string>:
var path = #"C:\test.txt";
var streamWriter = File.Exists(path) ? File.AppendText(path) : File.CreateText(path);
using (streamWriter)
{
streamWriter.WriteLine("NAME\tSURNAME\tAGE\tWORK");
foreach (string s in myList)
{
streamWriter.WriteLine(s.Replace(",", "\t"));
}
}

since you already have separator(","), so you can directly do the following for better performance, no need to convert:
var result = new StringBuilder();
result.AppendLine("NAME\tSURNAME\tAGE\tWORK");
myList.ForEach(i => result.AppendLine(i.Replace(",", "\t")));
System.IO.File.WriteAllText("foo.txt", result.ToString());

You could split them into strings like this:
String[] strings = myList[i].Split(',');
And then get them individually like this:
for(int i = 0; i < strings.Count; i++)
{
file.Write(strings[i] + " ");
}

Related

How can I split a string to store contents in two different arrays in c#?

The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}

Trying to count & List names in a txt file

I'm having some issues with the following:
I have a txt file with roughly two thousand names, with a bunch of duplicate entries. I'm trying to create something where it will list the amount of times a name appears. So for example:
John Doe | 48 times
Jane Doe | 20 times
etc etc.
I found examples here on how i could count this, but i have absolutely no idea how i could have this output this to a richTextbox or other file for example.
.Select(s => new { Key = s.Key, Count = s.Count()})
.ToDictionary(d => d.Key, d => d.Count);```
Data enter into the file names.txt file.
John Deo
John Deo
John Deo
John wick
John wick
Testing
Testing
I have made file into the project called names.txt and read him in code which are below.
string[] lines = File.ReadAllLines("../../names.txt");
Then grouping the names and print into the console application.
var mylines = lines.GroupBy(g => g).Select(s => new { Name = s, Count = s.Count() });
foreach (var line in mylines)
{
Console.WriteLine($"{line.Name.Key} | {line.Count}");
}
Result#
John Deo | 11
John wick | 2
Testing | 5
There are many different ways to do this. If all you want is to determine the counts and how it's displayed doesn't matter then you could output the counts to a CSV file and look at it with Excel. I don't know exactly how your names are formatted in the simple example below I assume one name per line.
class Program
{
static void Main(string[] args)
{
try
{
using (var reader = new StreamReader("names.txt"))
{
var names = GetNames(reader).ToLookup(k => k);
using (var writer = new StreamWriter("names.counted.csv"))
{
foreach (var name in names)
{
writer.WriteLine($"{name.Key},{name.Count()}");
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
}
static IEnumerable<string> GetNames(TextReader reader)
{
string line;
while ((line = reader.ReadLine()) != null)
yield return line;
}
}
Assumption:
Lets say we already have each line of the text file in an List<string> object we will call names and that each line in the text file represents a whole name spelled correctly.
Grouping/Printing the data:
Using LINQ we can group these values by themselves (similar to SQL) and then convert the IGrouping results into the objects we want to use later in our application. For example:
var totals = names.GroupBy(x => x)
.Select(group => new { Name = group.Key, Count = group.Count() });
foreach ( var total in totals )
{
Console.WriteLine($"{total.Name} | {total.Count} times");
}
Another option would be to use your existing code and just print out the values of the dictionary
var totals = names
.Select(s => new { Key = s.Key, Count = s.Count()})
.ToDictionary(d => d.Key, d => d.Count);
foreach ( var kvp in totals )
{
Console.WriteLine($"{kvp.Key} | {kvp.Value} times");
}
Saving/Displaying the data:
If you want to do something other then print to console you could simply manipulate the data into the value you want. For example if you want to save it to another file:
var csvContent = totals
.Select(total => $"{total.Name},${total.Count} times")
.ToArray();
File.WriteAllLines(filePath, csvContent);
Or you could create a string (e.g. in above: String.Join("\n", csvContent)) and update a RichTextBox like so
You could iterate over the results of your query and add each name/count to a StringBuilder, then output the final string to your RichTextBox:
StringBuilder sb = new StringBuilder();
foreach(var KVP in yourDictionaryVariableName)
{
sb.AppendLine(KVP.Key + " | " + KVP.Value.ToString());
}
richTextBox1.Text = sb.ToString();

How to make string list to "string array"

This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.

How can I check if a line contains specific string from a list of strings?

I have a string, and a list of strings called name. I'm trying to check if a line of my list of string contains a name in the list.
My string:
peter has
julia has
elvis has
carol has
Lines of this string:
string[] lines = mystring.Split(new string[] { "\r\n" }, StringSplitOptions.None);
My list of strings contains : peter and elvis.
So it would show:
peter checked
elvis checked
I tried:
for(int i =0;i < lines.Lenght;i++){
for(int x =0; x < mylist.Count;x++){
if(lines[i].Contains(mylist[x]){
textbox1.Text = textbox1.Text + mylist[x] + " checked";
}
}
}
How can I fix it?
To return just the strings in a list which contain a substring from another list (names), do something like this:
var result = lines.Where(line => names.Any(name => line.Contains(name)));
the following code doesn't look beautiful but at least works for me...
string[] line = { "peter has", "julia has", "elvis has", "carol has" };
string[] mylist = {"peter", "elvis"};
List<string> newitems = new List<string>();
string checkeditem;
foreach (var item in line)
{
foreach (var check in mylist)
{
if (item.Contains(check))
{
checkeditem = item.Replace("has", "checked");
newitems.Add(checkeditem);
}
}
}
//You can bind the newitems with your textbox1 here

C# easy way to convert a split string into columns

This is a rough one to explain. What I have is a string,
string startString = "Operations\t325\t65\t0\t10\t400"
string[] splitStart = startString.Split('\t');
I need to turn this into
Operations|325
Operations|65
Operations|0
Operations|10
Operations|400
The problem is i need this so be dynamic to if it has 10 splits I need it to do the same process 10 times, if it has 4, then it needs to do 4.
Any help would be awesome.
Sorry for any confusion, Operations is just this string, so it's not static. It really need to be [0] of the string split.
Something like:
string startString = "Operations\t325\t65\t0\t10\t400"
string[] splitStart = startString.Split('\t');
List<string> result = new List<string>();
if(splitStart.Length > 1)
for(int i = 1; i < splitStart.Length; i++)
{
result.Add(splitStart[0] + "|" + splitStart[i]);
}
If it is the strings you want, a little Linq should be fine:
string startString = "Operations\t325\t65\t0\t10\t400";
var operations = startString.Split('\t').Select(str => "Operations|" + str);
How about this?
var reFormatted = new List<string>();
foreach (var roughOne in toExplain)
{
// example of roughOne "Operations\t325\t65\t0\t10\t400"
var segments = roughOne.Split("\t");
var firstSegment = segments.First();
var sb = new StringBuilder();
foreach (var otherSegment in segments.Skip(1))
{
sb.Append(firstSegment);
sb.Append("|")
sb.Append(otherSegment);
sb.Append("\r\n");
}
reFormatted.Add(sb.ToString());
}

Categories