简体   繁体   中英

How do I convert List<Class> to String?

I've got an List and I want to convert it into string. Including all de strings and data that I've been added to my list.

This is my class

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

}

Then I declare it in that way:

List<MyClass> list = addDataToList("Passwd", "UserID");

So, how can I convert that list to String?

Thanks for any help.

如果要连接列表中的所有msg ,则可以使用string.Join

string str = string.Join(",", list.Select(r=> r.msg));
public class MyClass
{
   public Boolean success { get; set; }
   public String msg { get; set; }

   public override string ToString()
   {
     // return Whatever formalism of strings, e.g.
     return success? "Yeah":"Sorry" + msg;
   }
}

you could (no IDE):

List<MyClass> list;

var res = from a in list
          select String.Format("lala: {0} lili:{1}",a.success, a.msg);

or you could:

StringBuilder builder = new StringBuilder ();

foreach (a in list)
{
    builder.AppendFormat("lala: {0} lili:{1}\n",a.success, a.msg);
}

regarding second possibility, If you need formatting, i think my suggestion would be slightly faster, but Habib's one is definitely cooler...

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);    
}

Try this

for (int i = 0; i < list.Count; i++)
{
  var a = list[i];
  Console.WriteLine(builder.AppendFormat("lala: {0} lili:{1}\n", a.success, a.msg));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM