Jak dołączyć int [] do oddzielonego znakiem łańcucha in.NET?
Mam tablicę liczb całkowitych:
int[] number = new int[] { 2,3,6,7 };
Jaki jest najprostszy sposób na przekształcenie ich w pojedynczy ciąg znaków, gdzie liczby są oddzielone znakiem (np.: "2,3,6,7"
)?
10 answers
var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"
EDIT :
Widzę kilka rozwiązań reklamujących użycie StringBuilder. Ktoś skarży się, że metoda Join powinna przyjąć pewną liczbę argumentów.
Rozczaruję Cię:)Join wymaga tablicy z jednego powodu-wydajności. Metoda Join musi znać rozmiar danych, aby skutecznie wstępnie przydzielić wymaganą ilość pamięci.Oto część wewnętrznej implementacji String.Metoda łączenia:
// length computed from length of items in input array and length of separator
string str = FastAllocateString(length);
fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
{
UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
buffer.AppendString(value[startIndex]);
for (int j = startIndex + 1; j <= num2; j++)
{
buffer.AppendString(separator);
buffer.AppendString(value[j]);
}
}
Jestem zbyt leniwy, by porównywać wykonanie proponowanych metod. Ale coś mi mówi, że Join wygra:)Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-20 07:01:46
Chociaż OP określa. NET 3.5, ludzie chcący to zrobić w. NET 2.0 z C#2 mogą to zrobić:
string.Join(",", Array.ConvertAll<int, String>(ints, Convert.ToString));
Uważam, że istnieje wiele innych przypadków, w których użycie konwertera.xxx functions jest lepszą alternatywą dla lambda, chociaż w C#3 lambda może pomóc w wnioskowaniu typu.
Dość kompaktowa wersja C # 3, która współpracuje z. NET 2.0 to:
string.Join(",", Array.ConvertAll(ints, item => item.ToString()))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-22 10:33:16
Jedną z kombinacji tych dwóch metod byłoby napisanie metody rozszerzenia na IEnumerable
using System;
using System.Collections.Generic;
using System.Text;
public static class Extensions
{
public static string JoinStrings<T>(this IEnumerable<T> source,
Func<T, string> projection, string separator)
{
StringBuilder builder = new StringBuilder();
bool first = true;
foreach (T element in source)
{
if (first)
{
first = false;
}
else
{
builder.Append(separator);
}
builder.Append(projection(element));
}
return builder.ToString();
}
public static string JoinStrings<T>(this IEnumerable<T> source, string separator)
{
return JoinStrings(source, t => t.ToString(), separator);
}
}
class Test
{
public static void Main()
{
int[] x = {1, 2, 3, 4, 5, 10, 11};
Console.WriteLine(x.JoinStrings(";"));
Console.WriteLine(x.JoinStrings(i => i.ToString("X"), ","));
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-28 14:42:22
String.Join(";", number.Select(item => item.ToString()).ToArray());
Musimy przekonwertować każdy z elementów na String
, zanim będziemy mogli je połączyć, więc sensowne jest użycie Select
i wyrażenia lambda. Jest to odpowiednik map
w niektórych innych językach. Następnie musimy przekonwertować wynikową kolekcję łańcuchów z powrotem na tablicę, ponieważ String.Join
akceptuje tylko tablicę łańcuchów.
ToArray()
jest chyba trochę brzydki. String.Join
powinien naprawdę zaakceptować IEnumerable<String>
, nie ma powodu, aby ograniczać go tylko do tablic. To pewnie dlatego, że {[8] } jest z przed generics, kiedy tablice były jedynym rodzajem typed zbiór dostępny.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-28 14:05:24
Jeśli Twoja tablica liczb całkowitych może być duża, uzyskasz lepszą wydajność za pomocą Stringbuildera. Np.:
StringBuilder builder = new StringBuilder();
char separator = ',';
foreach(int value in integerArray)
{
if (builder.Length > 0) builder.Append(separator);
builder.Append(value);
}
string result = builder.ToString();
Edit: kiedy to zamieściłem, miałem błędne wrażenie, że " StringBuilder.Append (int value) " wewnętrznie udało się dopisać reprezentację string wartości całkowitej bez tworzenia obiektu string. Jest to błędne: sprawdzenie metody za pomocą reflektora pokazuje, że po prostu dodaje wartość.ToString().
Dlatego jedyna potencjalna różnica w wydajności jest to, że ta technika pozwala uniknąć tworzenia jednej tablicy i zwalnia łańcuchy do zbierania śmieci nieco wcześniej. W praktyce nie będzie to miało żadnej wymiernej różnicy, więc podałem to lepsze rozwiązanie .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:35
Pytanie dotyczy "najprostszego sposobu konwersji ich na pojedynczy ciąg znaków, w którym liczba jest oddzielona znakiem".
Najprostszym sposobem jest:
int[] numbers = new int[] { 2,3,6,7 };
string number_string = string.Join(",", numbers);
// do whatever you want with your exciting new number string
EDIT: to działa tylko w. NET 4.0+, przegapiłem wymóg. NET 3.5 za pierwszym razem, gdy przeczytałem pytanie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-05 00:35:47
Zgadzam się z wyrażeniem lambda pod względem czytelności i konserwacji, ale nie zawsze będzie to najlepsza opcja. Minusem korzystania z metod IEnumerable / ToArray i StringBuilder jest to, że muszą dynamicznie rozwijać listę, zarówno elementów, jak i znaków, ponieważ nie wiedzą, ile miejsca będzie potrzebne na końcowy ciąg.
Jeśli rzadki przypadek, w którym szybkość jest ważniejsza niż zwięzłość, poniżej jest bardziej efektywna.
int[] number = new int[] { 1, 2, 3, 4, 5 };
string[] strings = new string[number.Length];
for (int i = 0; i < number.Length; i++)
strings[i] = number[i].ToString();
string result = string.Join(",", strings);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-28 15:49:22
ints.Aggregate("", ( str, n ) => str +","+ n ).Substring(1);
Myślałem też, że jest prostszy sposób. Nie znam się na wydajności, ktoś ma jakiś (teoretyczny) pomysł?Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-08 16:15:12
W. NET 4.0, string join ma przeciążenie dla params object[]
, więc jest to tak proste, jak:
int[] ids = new int[] { 1, 2, 3 };
string.Join(",", ids);
Przykład
int[] ids = new int[] { 1, 2, 3 };
System.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM some_table WHERE id_column IN (@bla)");
cmd.CommandText = cmd.CommandText.Replace("@bla", string.Join(",", ids));
[7]} W. NET 2.0 jest to trochę trudniejsze, ponieważ nie ma takiego przeciążenia. Więc potrzebujesz własnej metody generycznej:
public static string JoinArray<T>(string separator, T[] inputTypeArray)
{
string strRetValue = null;
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
for (int i = 0; i < inputTypeArray.Length; ++i)
{
string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(str))
{
// SQL-Escape
// if (typeof(T) == typeof(string))
// str = str.Replace("'", "''");
ls.Add(str);
} // End if (!string.IsNullOrEmpty(str))
} // Next i
strRetValue= string.Join(separator, ls.ToArray());
ls.Clear();
ls = null;
return strRetValue;
}
W. NET 3.5 możesz użyć metod rozszerzeń:
public static class ArrayEx
{
public static string JoinArray<T>(this T[] inputTypeArray, string separator)
{
string strRetValue = null;
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
for (int i = 0; i < inputTypeArray.Length; ++i)
{
string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(str))
{
// SQL-Escape
// if (typeof(T) == typeof(string))
// str = str.Replace("'", "''");
ls.Add(str);
} // End if (!string.IsNullOrEmpty(str))
} // Next i
strRetValue= string.Join(separator, ls.ToArray());
ls.Clear();
ls = null;
return strRetValue;
}
}
Więc możesz użyć joinarray extension-method.
int[] ids = new int[] { 1, 2, 3 };
string strIdList = ids.JoinArray(",");
Możesz również użyć tej metody rozszerzenia w. NET 2.0, jeśli dodasz ExtensionAttribute do swojego kod:
// you need this once (only), and it must be in this namespace
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ExtensionAttribute : Attribute {}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-17 10:25:59
You can do
ints.ToString(",")
ints.ToString("|")
ints.ToString(":")
Sprawdź
Separator rozdzielany ToString dla Array, List, Dictionary, Generic IEnumerable
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-22 10:18:32