How can i use multiple delimiters in Array List - c#

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);

Related

C# - Get All Words Between Chars

I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);

LINQ unable to OrderBy date in specific column?

I have a CSV file which goes like this:
1,01/01/2001,a
2,19/09/2013,as
3,12/05/2016,asd
4,13/05/2016,asdf
5,12/12/2012,asdfg
6,05/02/2006,asdfgh
7,06/03/2011,asdfghj
I want to sort and display the dates in chronological order but I can't seem to get my code to sort it out. However, my code is able to display the dates according to the format in the CSV file.
If the CSV file is like this:
01/01/2001
19/09/2013
12/05/2016
13/05/2016
12/12/2012
05/02/2006
06/03/2011
Then, it works just fine.
The following is my code:
string parts = new StreamReader(#"C:\input.txt").ReadToEnd();
string[] file = parts.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < file.Length; i++)
{
string[] data = file[i].Split(new string[] { "," }, StringSplitOptions.None);
string[] dates = new string[] { data[1].ToString() };
//var date = dates.OrderBy(x => DateTime.Parse(x)).ToList();
var date = dates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));
foreach (string s in date)
{
sb.AppendLine(s + "<br />");
Label1.Text = sb.ToString();
}
}
I have tested this code using both DateTime.Parse and DateTime.ParseExact on the CSV file, but they didn't work.
I'm really new to LINQ query and this is my first time using it. I would really appreciate it if there is an explanation provided on what's wrong with my code.
You are sorting an array (dates) that always contains one date (because you create it each time from a single line in a loop). Then you add this line to the label's text.
You have to create a collection that contains all the dates, before you sort it.
string parts = new StringReader(#"C:\input.txt").ReadToEnd();
string[] lines = parts.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
List<string> dates = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
string[] data = lines[i].Split(new string[] { "," }, StringSplitOptions.None);
dates.Add(data[1]);
}
var datesSorted = dates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));
foreach (string s in datesSorted)
{
sb.AppendLine(s + "<br />");
}
Label1.Text = sb.ToString();
It may required to select the values in Date format first then order it
Try
var date = dates.Select(x => DateTime.ParseExact(x, "dd/MM/yyyy", null)).OrderBy(t => t).ToList();
foreach (DateTime s in date)
{
sb.AppendLine(s.ToString("dd/MM/yyyy") + "<br />");
}
Label1.Text = sb.ToString();
Need to move the Label1 Text assigning after foreach
Please first put your dates into a Collection, for example a List or Array, and then sort the Collection. Default sort order is ascending
List<string> unsortedDates = new List<string>();
string parts = new StreamReader(#"C:\input.txt").ReadToEnd();
string[] file = parts.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < file.Length; i++)
{
string[] data = file[i].Split(new string[] { "," }, StringSplitOptions.None);
unsortedDates.Add(data[1]);
}
var sortedDatesAscending = unsortedDates.OrderBy(x => DateTime.ParseExact(x, "dd/MM/yyyy", null));
foreach (string s in sortedDatesAscending)
{
sb.AppendLine(s + "<br />");
Label1.Text = sb.ToString();
}

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

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?

formatting string in C#

How can I convert this list of strings to comma separated value enclosed within quotes without any escape characters?
{"apple", "berry", "cherry"} => well, ""apple", "berry", "cherry""
If I understood you correctly,
"\"" + String.Join("\", \"", new string[]{"apple","berry","cherry"}) + "\"";
or, alternatively,
String.Format("\"{0}\"", String.Join("\", \"", new string[] {"apple","berry","cherry"}));
Read more on System.String.Join(...).
Hope this will do the job
var ar = new []{ "apple", "berry", "cherry" };
var separator = "\",\"";
var enclosingTag = "\"";
Console.WriteLine ( enclosingTag + String.Join(separator, ar) + enclosingTag );
If you are using C#:
using System;
string[] arr = new string[] { "apple", "berry", "cherry" };
string sep = "\",\"";
string enclosure = "\"";
string result = enclosure + String.Join(sep, arr) + enclosure;

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