Reputation:
In a list, I'm having some string values based on certain condition.
I need to concatenate the string value with another string "SUM()"
.
For eg:List contains values A1
, A2
, A3
The output string should be
Sum(A1) as A1,Sum(A2) as A2,Sum(A3) as A3
My code is as follows:
List<string> strList = new List<string>();
foreach (DataRow dr in dt.Rows)
{
strList .Add(dr[0].ToString());
}
string NewStrSum = "";
string NewColSum = "";
NewStrSum = " SUM(";
NewColSum = NewStrSum + String.Join(") ", strList .Select(n => n.ToString()).ToArray());
But the output is Sum(A1)A2
Upvotes: 1
Views: 105
Reputation: 74
You can use as below,
// This is your code
List<string> strList = new List<string>();
foreach (DataRow dr in dt.Rows)
{
strList .Add(dr[0].ToString());
}
// New Code
string newColSum = string.Join(",", strList.Select(s => string.Format("SUM({0}) as {0}", s)));
Upvotes: 0
Reputation: 144
Try to concat the strings inside the bucle foreach
here an example:
string OutPut = string.Empty;
foreach (DataRow dr in dt.Rows)
{
OutPut += "SUM("
+ dr[0].ToString()
+ ") as ";
+ dr[0].ToString()
+", ";
}
Upvotes: 0
Reputation: 1107
string result = string.Empty;
for(int i=0;i<strList.Count;i++)
{
if(i!=0)
result+= " , ";
result+= "Sum("+strList[i]+") as "+strList[i];
}
Upvotes: 0
Reputation: 24916
Why don't you use something like this:
// Create your list
var list = new List<string>();
list.Add("A1");
list.Add("A2");
list.Add("A3");
// Create list of elements that look like 'Sum(X) as X':
var sumList = list.Select(x=>string.Format("Sum({0}) as {0}", x));
// Create single string
var result = string.Join(", ", sumList);
Console.WriteLine(result);
Upvotes: 1
Reputation: 98868
You can use Enumerable.Select
to get every element in your List<string>
with specified formatted and use it with string.Join
to concatenate them with ,
as;
var list = new List<string>() {"A1", "A2", "A3"};
var newlist = list.Select(s => string.Format("SUM({0}) as {0}", s));
var result = string.Join(",", newlist);
result
will be;
SUM(A1) as A1,SUM(A2) as A2,SUM(A3) as A3
Upvotes: 4
Reputation: 305
Try this:
var list = new List<string> {"A1", "A2", "A3"};
var str = list.Aggregate(string.Empty, (current, item) => current + string.Format("SUM({0}) AS {0},", item));
str = str.Remove(str.Length - 1);
Upvotes: 0