喜歡的東西String.Join(",", new string[] { "a", "b" });
,但Guid[]
如何將Guid []轉換爲String?
var guids = new Guid[] { Guid.Empty, Guid.Empty };
var str = /* Magic */
// str = 00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000
喜歡的東西String.Join(",", new string[] { "a", "b" });
,但Guid[]
如何將Guid []轉換爲String?
var guids = new Guid[] { Guid.Empty, Guid.Empty };
var str = /* Magic */
// str = 00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000
var str = guids.Select(g => g.ToString())
.Aggregate((working, next) => working + "," + next);
一旦你的GUID列表開始增長,拼接的這種方法將會導致性能問題。您可以修改它以使用StringBuilder:
var str = guids.Select(g => g.ToString())
.Aggregate(new StringBuilder(),
(sb, str) => sb.Append("," + str),
sb => sb.ToString());
這兩者都是複雜的LINQ擴展方法。如果你的框架> = NET 3.5
String.Join(",", (from g in guids select g.ToString()).ToArray())
我認爲這將工作?
StringBuilder stringBuilder = new StringBuilder();
int i = 0;
foreach (var guid in guids)
{
stringBuilder.Append(guid.ToString());
if (++i < guids.Length)
{
stringBuilder.Append(",");
}
}
var str = stringBuilder.ToString();
String.Join(",", guids.Select(g => g.ToString()).ToArray());
偉大&簡單的答案 – 2010-07-26 15:22:23
.NET 4增加了一個通用的'加入'方法,你可以不加修改地傳遞'guids'數組 – thecoop 2010-07-26 15:32:43
@thecoop:注意,謝謝。 – 2010-07-26 15:33:52
:你也可以簡單地使用的string.join。所以,在.NET 4中,只是這將工作:
String.Join(",", guids);
.NET 4中添加一個String.Join<T>(string separator, IEnumerable<T> values
方法
var str = String.Join(",", guids.Select(g => g.ToString()).ToArray());
很高興知道,謝謝。 – BrunoLM 2010-07-26 18:52:58
String.Join(",", Array.ConvertAll(guids, g => g.ToString()));
看來這個聲明無法在VS2010中通過編譯? – Thomson 2010-07-26 15:48:08
Array.ConvertAll需要一個實現'Converter
//Convert string to List<string>
List<string> guidList = your_string.Split(',').ToList<string>();
//Convert string to List<Guid>
List<Guid> guidList = your_string.Split(',').ToList<string>().ConvertAll<Guid>(g => new Guid(g));
哇,完美!謝謝! – BrunoLM 2010-07-26 15:19:01
@布魯諾,將它標記爲接受的答案,如果它是爲你工作的! :-) – DaveDev 2010-07-26 15:20:55
與其他方法相比,我很好奇它的工作速度。我猜Aggregate不使用String.Concat正確分配內存。 – 2010-07-26 15:23:01