在列表中,我根据特定条件获得了一些字符串值。
我需要将字符串值与另一个字符串"SUM()"
连接起来。
例如:列表包含值A1
,A2
,A3
输出字符串应为
总和(A1)为A1,总和(A2)为A2,总和(A3)为A3
我的代码如下:
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());
但输出为Sum(A1)A2
答案 0 :(得分:4)
您可以使用Enumerable.Select
获取指定格式的List<string>
中的每个元素,并将其与string.Join
结合使用,以,
为其连接;
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
将是;
SUM(A1) as A1,SUM(A2) as A2,SUM(A3) as A3
答案 1 :(得分:1)
为什么不使用这样的东西:
// 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);
答案 2 :(得分:0)
试试这个:
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);
答案 3 :(得分:0)
string result = string.Empty;
for(int i=0;i<strList.Count;i++)
{
if(i!=0)
result+= " , ";
result+= "Sum("+strList[i]+") as "+strList[i];
}
答案 4 :(得分:0)
尝试连接bucle foreach
中的字符串这里有一个例子:
string OutPut = string.Empty;
foreach (DataRow dr in dt.Rows)
{
OutPut += "SUM("
+ dr[0].ToString()
+ ") as ";
+ dr[0].ToString()
+", ";
}
答案 5 :(得分:0)
您可以按照以下方式使用
// 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)));