经常需要将一个数组或者List的各项通过分隔符连接成字符串。一般的实现逻辑是通过成员+分隔符连接,然后在结果截掉最后一个分隔符。突然,发现String.Join方法实现的正是这一功能。一个简单的例子输出a,b,c
class Program
{
static void Main(string[] args)
{
List<string> list=new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");
Console.WriteLine(string.Join(",",list));
Console.ReadKey();
}
}
结果: a b c
数组:string[] s = { "a", "b", "c", "d", "e" };
①Join转换字符串:string str1 = string.Join(",", s);
②格式化字符串:string str2 = String.Format("{0},{1},{2},{3},{4}", s);
string[] sl = new string[]{"aa","bb","cc"};
string s;
s = String.Join("", sl);
测试过,结果为:aabbcc
s = String.Join(",", sl);
结果为:aa,bb,cc
将List<string> 转换为 字符串:
List<string> listStr = new List<string>();
listStr.Add("a");
listStr.Add("b");
listStr.Add("c");
//以下代码实现:将listStr转换为一串以‘,’分隔开的字符串并显示出来
string myStr = string.Join(",", listStr.ToArray());
MessageBox.Show(myStr);
//显示结果 a,b,c
string[] str = new string[] { "a", "b", "c" };
//以下代码实现:将listStr转换为一串以‘,’分隔开的字符串并显示出来
string myStr = string.Join(",", str);
MessageBox.Show(myStr);
//显示结果 a,b,c
以上是将数组转换为 字符串的例子。 如不需要分隔符则可以以""参数 为空。
有分隔符也挺好啦,可用string.split方法再进行转换为数组使用,很多时候都会用到的。
也是直接贴代码上来了
string str = "a,b.c";
string[] strArray= str.Split(','); //以“,”为分隔符,将str字符串 转换为数组。
MessageBox.Show(strArray[0]); //显示出 a
從數據庫中獲取List<string>,再轉化成字符串:
string names = string.Join(",",num);
显示结果:
周丽秀,球球,球球1
数据库语句中显示:
select "BOOKID","产品别","ProjectName","Rev","Major人员","LayoutLeader","实际开始作业日","实际出图日" from "LayoutProjectInfo"."Project信息表" WHERE (now()::timestamp)::date-("实际出图日"::timestamp)::date=1 AND "Major人员" IS NOT NULL AND POSITION ('Pending' IN "Rev") = 0 AND POSITION ('TR' IN "Rev") = 0 AND "LayoutLeader" NOT IN ('周丽秀,球球,球球1')
string names = string.Join("','", num);
结果:
周丽秀','球球','球球1
steSql = "select "BOOKID","產品別","ProjectName","Rev","Major人員","LayoutLeader","實際開始作業日","實際出圖日" from "LayoutProjectInfo"."Project資訊表" WHERE (now()::timestamp)::date-("實際出圖日"::timestamp)::date=3 AND "Major人員" IS NOT NULL AND POSITION ('Pending' IN "Rev") = 0 AND POSITION ('TR' IN "Rev") = 0 AND "LayoutLeader" NOT IN ('" + names + "')";
注意: AND "LayoutLeader" NOT IN ('" + names + "')";這names裏面存在兩個單引號
数据库语句中显示:
select "BOOKID","产品别","ProjectName","Rev","Major人员","LayoutLeader","实际开始作业日","实际出图日" from "LayoutProjectInfo"."Project信息表" WHERE (now()::timestamp)::date-("实际出图日"::timestamp)::date=1 AND "Major人员" IS NOT NULL AND POSITION ('Pending' IN "Rev") = 0 AND POSITION ('TR' IN "Rev") = 0 AND "LayoutLeader" NOT IN** ('周丽秀','球球','球球1')**
网友评论