Convert a List to a String in C#

Convert a list to a string in C#

Maybe you are trying to do

string combinedString = string.Join( ",", myList.ToArray() );

You can replace "," with what you want to split the elements in the list by.

Edit: As mentioned in the comments you could also do

string combinedString = string.Join( ",", myList);

Reference:

Join<T>(String, IEnumerable<T>) 
Concatenates the members of a collection, using the specified separator between each member.

Convert a list of strings to a single string

string Something = string.Join(",", MyList);

How to convert List to a string and back

If you have a lot of users and a lot of columns, it would be better to write your own custom converter class.

public static class UsersConverter
{
// Separates user properties.
private const char UserDataSeparator = ',';

// Separates users in the list.
private const char UsersSeparator = ';';

public static string ConvertListToString(IEnumerable<User> usersList)
{
var stringBuilder = new StringBuilder();

// Build the users string.
foreach (User user in usersList)
{
stringBuilder.Append(user.Name);
stringBuilder.Append(UserDataSeparator);
stringBuilder.Append(user.Age);
stringBuilder.Append(UsersSeparator);
}

// Remove trailing separator.
stringBuilder.Remove(stringBuilder.Length - 1, 1);

return stringBuilder.ToString();
}

public static List<User> ParseStringToList(string usersString)
{
// Check that passed argument is not null.
if (usersString == null) throw new ArgumentNullException("usersString");

var result = new List<User>();

string[] userDatas = usersString.Split(UsersSeparator);

foreach (string[] userData in userDatas.Select(x => x.Split(UserDataSeparator)))
{
// Check that user data contains enough arguments.
if (userData.Length < 2) throw new ArgumentException("Users string contains invalid data.");

string name = userData[0];
int age;

// Try parsing age.
if (!int.TryParse(userData[1], out age))
{
throw new ArgumentException("Users string contains invalid data.");
}

// Add to result list.
result.Add(new User { Name = name, Age = age });
}

return result;
}
}

You will win performance wise using the StringBuilder to build up your users string. You could also easily expand the converter to take account different separators/additional logic etc.

If you need a more generic solution (to be able to use for any class), you could create a converter which uses reflection to iterate over all the public fields, get/set properties to see what can be extracted as string and later reverse the process to convert your string back to the list.

C# Object List to String List

var mylist = myObjectList.ConvertAll(x => x.ToString());

Edit

  var mylist = myObjectList.ConvertAll(x => Convert.ToString(x));

thanks Scott Chamberlain

To get first array of objects

var mylist = (myObjectList.First() as object[]).ToList()
.ConvertAll(x=>Convert.ToString(x));

To add rest to the list.

mylist.AddRange(mylist.GetRange(1,myObjectList.Count-2).ConvertAll(x=>Convert.ToString(x)));

Converting an Object List to a String List

Yes you can use LINQ. Like this:

List<string> managerList = matchedManager.Select(m => m.FullName).ToList();

C#: Converting List of Chars to String

One option for this is to use the string constructor:

var myString = new string(array1.ToArray());

C# List string to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

How do I convert List Class to String?

Here's a way to convert List<Class> to String ,

and I append the way to convert the converted String back to List , too.

.

The MyClass class :

public class MyClass
{
public Boolean success { get; set; }
public String msg { get; set; }

// class to string
public override string ToString()
{
return success.ToString() + "," + msg;
}

public MyClass(){}

// string to class
public MyClass(string myclassTostring)
{
string[] props = myclassTostring.Split(',');
success = Convert.ToBoolean(props[0]);
msg = props[1];
}

}

The convert way:

///  Produce a List ///
List<MyClass> myclassList =
new List<MyClass>()
{
new MyClass(){success = true, msg = "1suc"},
new MyClass(){success = false, msg = "2fail"},
new MyClass(){success = true, msg = "3suc"},
new MyClass(){success = true, msg = "4suc"},
new MyClass(){success = false, msg = "5fail"},
};

/// List Convert To String ///
string myclassListToString =
String.Join(";", myclassList.Select(o => o.ToString()));

Console.WriteLine(myclassListToString);


/// String Convert Back To List ///
string[] myclassToStrings = myclassListToString.Split(';');
List<MyClass> convertBackList =
myclassToStrings.
Select(myclassTostring => new MyClass(myclassTostring)).ToList();

Edit:

Few months later I'm touching C# ASP.NET WebAPI and I found that the JSON format is frequently used in all kinds of api,

and JSON is an powerful convenient way to turn data to string and turn back to data, it can auto turn any kind of object, array, class you can think to string, and auto turn back.

The Keyword is JSON Serialize Deserialize, google it and you can find many ready-made package.

And I know one of famous of it is NewtonSoft JSON, and Microsoft may have its own library for JOSN process, too.

For example something like:

    public static string ToJSON(this object obj)
{
var serializer = new JavaScriptSerializer();
try
{
return serializer.Serialize(obj);
}
catch (Exception ex)
{
return "";
}
}

and if you install Nuget Package NewtonSoftJson, you can use

public static string ToJSON(object obj)
{
return JsonConvert.SerializeObject(obj);
}


Related Topics



Leave a reply



Submit