DataTable tblData = new DataTable();
MySQLProcessor.dtTable(pullDataQuery, out tblData);
foreach (DataRow columnRow in tblData.Rows)
{
//do string work here
}
columnRow looks like this
[0]Apple
[1]Pear
[2]Mango
I want to turn it into a string that looks like Apple|Pear|Mango
without doing a foreach loop in the array.
Soryr for not making it clear, each table comes out with a different amount of arrayitems.
Try doing
object[] arr = new object[] {"1", "2" };
string joinedStr = string.Join("|",arr.Select(p => p.ToString()).ToArray());
So, your code could become
DataTable tblData = new DataTable();
string myStr = string.Empty;
MySQLProcessor.dtTable(pullDataQuery, out tblData);
foreach (DataRow columnRow in tblData.Rows)
{
myStr = string.Join("|",columnRow.ItemArray.Select(p => p.ToString()).ToArray());
//do whatever you want
}
Consider String.Join. The columns values in question must be extracted first, perhaps...
var cols = row.ItemArray
.Select(i => "" + i) // Not i.ToString() so when i is null -> ""
.ToArray(); // For .NET35 and before, .NET4 Join takes IEnumerable
var res = string.Join("|", cols);
...or similar.
Happy coding.
Mike you can do something like this
string finalString=string.Empty;
foreach (DataRow columnRow in tblData.Rows)
{
finalString+=columnRow["ColumnName"]+"|";
}
if(finalyString.length>0)
{
finalyString=finalString.Substring(0,finalString.length-1) // this removes extra "|" at the end
}
//Without Using LINQ. In case you use old DotNet (Eg.2.0)
string ArrToStr(DataRow r,string separator)
{
string temp = "";
Object[] o = r.ItemArray;
foreach(Object oo in o)
{
temp += oo.ToString() + separator;
}
return temp;
}
//So you can use like this.
string value="";
foreach (DataRow row in combine.Rows)
{
value += ArrToStr(row, ",") ;
}
[Edited]:
You can get all the values of DataRow by it's property ItemArray.
ItemArray is array of values which data types are types of object.
You can pass this array to function string.Join() which concatenates all the elements of array, using the specified separator between each element.
Be carefull because if your DataRow contains DBNull.Value in any of the columns, function string.Join() will implicity convert DBNull.Value into empty string (""). So in the end you can get something like this A||B.
To avoid this situation I used in my example LINQ function Where() to get rid of empty values of DataRow and turn it into array again by using LINQ function ToArray(). More about DBNull.Value.ToString() you can find here msdn source .
In foreach loop you can notice that I have used dollar sign - $ (special character which identifies interpolated string), which is used for string interpolation.
"String interpolation is the process of evaluating a string literal
containing one or more placeholders, yielding a result in which the
placeholders are replaced with their corresponding values"
In this case placeholder is enclosed in a pair of curly brackets {}.
By using string interpolation I got rid of another + sign operator for concatenating string literal "\r\n".
string str = "";
foreach (DataRow columnRow in tblData.Rows)
{
str += $"{string.Join("|", columnRow.ItemArray.Where(val => val != DBNull.Value).ToArray())}\r\n";
}
Try this:
string record = columnRow[0].ToString() + "|" + columnRow[1].ToString() + "|" + columnRow[2].ToString();
Related
My code is as below:
List<string> colorList = new List<string>();
....
sCombo = reader["Combo"].ToString();
colorList.Add(sCombo.ToString());
....
foreach (var Combo in colorList)
{
Response.Write(string.Join(",", Combo));
}
Output: D410D430D440D420 instead of D410,D430,D440,D420
What is the most simple way to convert the List<string> into a comma-separated string?
EDIT #01
Your suggestion working, but I need this new output :
'D410','D430','D440','D420'
Because use this string on sql query.
Thank you
I think this would be very handy
var colorList = new List<string>() { "D410", "D430", "D440", "D420" };
string commaSeparated = string.Join(",", colorList);
Console.WriteLine(commaSeparated);
or try solution based on Linq
Console.WriteLine(colorList.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(','));
The output
D410,D430,D440,D420
Edit
string result = string.Join(",", colorList.Select(e => "'" + e + "'"));
Console.WriteLine(result);
will give you
'D410','D430','D440','D420'
Without a foreach:
Response.Write(string.Join(",", colorList));
You need to output like this => 'D410','D430','D440','D420'
So try below,
string result = string.Join(",", colorList.Select(x => $"'{x}'"));
Response.Write(result);
What we did above?
Answer: First we flatten each item in your list with a single quoted ('') surrounding string and then we just pass this newly generated flatten result to join method of string with a comma (,) to get your desired output.
Output: (From Debugger)
I'm working on an importer that takes tab delimited text files. The first line of each file contains 'columns' like ItemCode, Language, ImportMode etc and there can be varying numbers of columns.
I'm able to get the names of each column, whether there's one or 10 and so on. I use a method to achieve this that returns List<string>:
private List<string> GetColumnNames(string saveLocation, int numColumns)
{
var data = (File.ReadAllLines(saveLocation));
var columnNames = new List<string>();
for (int i = 0; i < numColumns; i++)
{
var cols = from lines in data
.Take(1)
.Where(l => !string.IsNullOrEmpty(l))
.Select(l => l.Split(delimiter.ToCharArray(), StringSplitOptions.None))
.Select(value => string.Join(" ", value))
let split = lines.Split(' ')
select new
{
Temp = split[i].Trim()
};
foreach (var x in cols)
{
columnNames.Add(x.Temp);
}
}
return columnNames;
}
If I always knew what columns to be expecting, I could just create a new object, but since I don't, I'm wondering is there a way I can dynamically create an object with properties that correspond to whatever GetColumnNames() returns?
Any suggestions?
For what it's worth, here's how I used DataTables to achieve what I wanted.
// saveLocation is file location
// numColumns comes from another method that gets number of columns in file
var columnNames = GetColumnNames(saveLocation, numColumns);
var table = new DataTable();
foreach (var header in columnNames)
{
table.Columns.Add(header);
}
// itemAttributeData is the file split into lines
foreach (var row in itemAttributeData)
{
table.Rows.Add(row);
}
Although there was a bit more work involved to be able to manipulate the data in the way I wanted, Karthik's suggestion got me on the right track.
You could create a dictionary of strings where the first string references the "properties" name and the second string its characteristic.
foreach (set.row officeJoin in officeJoinMeta)
{
foreach (set.somethingRow confRow in myData.something.Rows)
{
string dep = confRow["columnName"].ToString();
depts.Add(dep);
}
}
I've got this for-loop going through a column, adding each value in a column to dep, and later storing all these in a List < String > depts which i defined at the top of this method.
Some of the values in the dep are single strings like "R" but some are need to be separated after the comma "R,GL,BD".
I understand using .Split(","), but how do i split strings--how do i get each value in the array, split them with the comma, then store them in another array?
Written based on what you've explained:
foreach (set.row officeJoin in officeJoinMeta)
{
foreach (set.somethingRow confRow in myData.something.Rows)
{
string dep = confRow["columnName"].ToString();
depts.AddRange(dep.Split(','));
}
}
declare as
List<string[]> depts = new List<string[]>()
and add as
depts.Add(dep.Split(','));
List<string> depts=new List<dept>();
var values=dept].Split(',');
for(int index=0;index<values.length;index++)
{
depts.Add(values[index].ToString());
}
hihi
i have a question that i want to ask about c# and window form
i have this data... A,B,C; A1,B1,C1; A2,B2,C2; (this data is not hardcoded, it can continue to change, when more data insert come in) , i select this database column which is name as ColABC , and i retrieve and put in the datagridview ,
So is possible to always get the middle data?....but it is always this format record1 data, record1 data, record1; record2 data, record3 data, record...and so i want this data all the middle value retrieve out to this become this B,B1,B2.......so on...
ID | ColABC
1 | A,B,C; A1,B1,C1; A2,B2,C2;
This is like my DataGridView, the above.
The only thing i know is use split by ; first then by ,.
Is there any direct way?
Something like this, I try:
string[] doll = null;
doll = Convert.ToString(DGV.CurrentRow.Cells[0].Value).Split(';');
Basically like example the above code, doll get the " A,B,C; A1,B1,C1; A2,B2,C2; " this data which i retrieve from datagridview, so if i declare roll[0] it will give me "A,B,C", like what i mention above the data will change so how am i get the middle value always??
var input = "A,B,C; A1,B1,C1; A2,B2,C2;";
var resultList = Regex.Matches(input, #".*?,(.*?),.*?;")
.Cast<Match>()
.Select(arg => arg.Groups[1].Value)
.ToList();
var firstValue = resultList[0];
var secondValue = resultList[1];
// bind to a combobox
comboBox1.DataSource = resultList;
var comaSeparatedString = string.Join(",", resultList);
string testString = "A,B,C; A1,B1,C1; A2,B2,C2;";
Regex rgx = new Regex("[^,]+,([^,]+),[^,]+");
List<string> whatYouWant = testString.Split(';').Select(a => rgx.Replace(a, "$1")).ToList();
or
string testString = "A,B,C; A1,B1,C1; A2,B2,C2;";
Regex rgx = new Regex("[^,;]+,([^,;]+),[^,;]+;?");
for(Match m = rgx.Match(testString); m.Success; m = m.NextMatch())
{
Console.WriteLine(m.Groups[1].Value);
}
What about this.... Not in my device, to test this code... Still this is the approach...
foreach(DataGridViewRow dgvr in Datagridview.Rows){
if(dgvr!=null){
string middlevalues="";
string testString= dgvr.Cells[ColumnIndex].Value.ToString();
//If this string is string testString = "A,B,C; A1,B1,C1; A2,B2,C2;";
string[] basesplit = testString.Split(';');
int i=0;
foreach(string words in baseplit){
if(i<baseplit.Count-1){
middlevalues=words.Split(',')[1].ToString()+','
}else{ middlevalues=words.Split(',')[1].ToString();
i++;
}
}
}
}
i have a list of objects in a collection. Each object has a string property called Issue. I want to concatenate the issue from all of the items in the collection and put them into a single string. what is the cleanest way of doing this using LINQ.
here is manual way:
string issueList = "";
foreach (var item in collection)
{
if (!String.IsNullOrEmpty(item.Issue)
{
issueList = issueList + item.Issue + ", ";
}
}
//Remove the last comma
issueList = issueList.Remove(issueList.Length - 2);
return issueList;
You can write
return String.Join(", ", collection.Select(o => o.Issue));
In .Net 3.5, you'll need to add .ToArray().
You could use ToDelimitedString from morelinq.