Convert from 'string' to 'System.Collections.Generic.IEnumerable<string> - c#

Here is my code :
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0]);
System.IO.File.WriteAllLines(#"c:\temp\WriteLines.txt", query);
I want to convert quert to string so I can edit it , like this code for example
string[] res = s.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
I can use res[0].Substring and res[0].PadRight many options in text
So how can I convert my first code to become string but do same function?

I'm assuming that your file looks like this (Like grid):
Text11 Text12 Text13 Text14
Text21 Text22 Text23 Text24
Text31 Text32 Text33 Text34
Now you want to split it by cells so:
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)).ToList();
Now when you writing this back to the file you should join the lines:
System.IO.File.WriteAllLines(#"c:\temp\WriteLines.txt", query.Select(line => String.Join(" ", line)));
And when you want to edit cell you can use:
query[row][column].Substring();

You can simply add .ToArray() at the end :
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0])
.ToArray();
So you can do like query[0].Substring and query[0].PadRight.
Is that what you want?

Related

Parse text inbetween tabs

I have to copy and paste excel into a form and extract each value and since it's separated by tabs I'm doing something like:
var lines = PasteText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
foreach (var currLine in lines.Where(x => !String.IsNullOrWhiteSpace(x)))
{
var items = currLine.Split(new string[] { "\t", " " }, StringSplitOptions.RemoveEmptyEntries)
.Take(15).ToArray();
}
But a problem arises if there's a tab inside one of the column fields.
How could I go about solving this?

String.join array from last element

I have a scenario where I am getting a comma separated string LastName, FirstName. I have to convert it into FirstName LastName.
My code is below:
Public static void main(string [] args)
{
var str = "Lastname, FirstName":
var strArr = str.Split(',');
Array. Reverse(strArr);
var output = string.join(" ", strArr);
}
Is there a better way to do this, like in one line or using LINQ?
Yes there is already a Reverse extension method for IEnumerables:
var output = string.Join(" ",str.Split(',').Reverse());
This takes care of a lot of the various edge cases. You mentioned one but did not include it in your initial question so I assume there could be others.
var tests = new[]{"Lastname, FirstName", "Lastname, ", ", FirstName", "Lastname", "FirstName"};
foreach(var str in tests)
{
var strArr = str.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Reverse()
.Select(x => x.Trim());
var output = string.Join(" ", strArr);
Console.WriteLine(output);
}
Working Fiddle
Use Aggregate and Trim your names after splitting, you do not need reversing.
str.Split(',').Aggregate((lname, fname) => fname.Trim() + " " + lname.Trim())
Below is my new code:
Public static void main(string [] args)
{
var str = "Lastname, FirstName":
var strArr = str.Split(',').Select(p=>p.Trim()).ToArray();
var output = string.join(" ", strArr.Reverse());
}

How can i use multiple delimiters in Array List

I want to ask you about the below code:
string[] seledCats = new string[0];
string condsCats = EzCoding.Web.UI.QueryStringParsing.GetValue(
"CondsCats",
EzCoding.Web.RequestMethod.Post);
if (condsCats != null)
{
seledCats = condsCats.Split(new string[] { "," },
StringSplitOptions.RemoveEmptyEntries);
}
After insert the selected data in the array list, output like that A1,A2,
But I want to show it like that this one 'A1','A2'
So, How can i do it ?
Thanks.
You can use this little LINQ query:
string condsCats = EzCoding.Web.UI.QueryStringParsing.GetValue("CondsCats",EzCoding.Web.RequestMethod.Post);
string[] seledCats = null;
if(condsCats != null)
seledCats = condsCats
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => String.Format("'{0}'", s))
.ToArray();
seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string s = "'" + string.Join("','", seledCats) + "'";
//to split into array again...
seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

Adding a Newline

The code below adds the characters \r\n to my string variable but once the string is returned the Newline is ignored.
Here is a snippet of the returned string: Mondavi\r\nrms_processtype
And here is the code where I add a Newline:
char[] charsToTrim = { ',', ' ' };
feed = feed.TrimEnd(charsToTrim) + Environment.NewLine;
Here's the code that error's when it attempts to read the "feed" variable
var dict = feed.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
.SelectMany(s => s.Split('|')).ToDictionary(t => t.Split(',')[0], t => t.Split(',')[1]);
Try StringSplitOptions.RemoveEmptyEntries

C# convert DOMAIN\USER to USER#DOMAIN

I currently have the following code:
string user = #"DOMAIN\USER";
string[] parts = user.Split(new string[] { "\\" }, StringSplitOptions.None);
string user = parts[1] + "#" + parts[0];
Input string user can be in one of two formats:
DOMAIN\USER
DOMAIN\\USER (with a double slash)
Whats the most elegant way in C# to convert either one of these strings to:
USER#DOMAIN
Not sure you would call this most elegant:
string[] parts = user.Split(new string[] {"/"},
StringSplitOptions.RemoveEmptyEntries);
string user = string.Format("{0}#{1}", parts[1], parts[0]);
How about this:
string user = #"DOMAIN//USER";
Regex pattern = new Regex("[/]+");
var sp = pattern.Split(user);
user = sp[1] + "#" + sp[0];
Console.WriteLine(user);
A variation on Oded's answer might use Array.Reverse:
string[] parts = user.Split(new string[] {"/"},StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(parts);
return String.Join("#",parts);
Alternatively, could use linq (based on here):
return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
.Aggregate((current, next) => next + "#" + current);
You may try this:
String[] parts = user.Split(new String[] {#"\", #"\\"}, StringSplitOptions.RemoveEmptyEntries);
user = String.Format("{0}#{1}", parts[1], parts[0]);
For the sake of adding another option, here it is:
string user = #"DOMAIN//USER";
string result = user.Substring(0, user.IndexOf("/")) + "#" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1));

Categories