如何将List转换为字符串并返回

时间:2013-02-16 17:00:48

标签: c# .net linq list

我从数据库中检索了一个用户列表,比如

List<User> users = <..list of users from db...> 

名称,姓氏,DateOfBirth //多维数组??

现在我想把这个列表存储为一个字符串,我希望能够重用它,即

string strUsers = users.ToArray().ToString();

如何从strUsers重新创建用户列表?

有可能吗?

4 个答案:

答案 0 :(得分:8)

使用string.Join方法,例如

var joined = string.Join(",", users.Select(u => u.Name));

这将为您提供一个用','分隔的用户名的单个字符串。

或多列:

var joined = string.Join(",", 
                 users.Select(u => u.FirstName + " " + u.LastName ));

您可以使用string.Split来反转该过程,例如

var split = joined.Split( new [] {','} );

答案 1 :(得分:2)

如果你有很多用户和很多列,那么编写自己的自定义转换器类会更好。

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

使用StringBuilder构建用户字符串,您将获得性能提升。您还可以轻松扩展转换器以考虑不同的分隔符/其他逻辑等。

如果您需要更通用的解决方案(能够用于任何类),您可以创建一个转换器,它使用反射迭代所有公共字段,获取/设置属性以查看可以提取为字符串的内容和稍后反转该过程以将您的字符串转换回列表。

答案 2 :(得分:1)

我认为您正在寻找的东西可以让您将所有用户转储到字符串并让用户从字符串中恢复,对吗?

我建议这样的事情: 添加一个将XElement返回给Users类型的方法:

public XElement GetXElement()
{
    return new XElement("User", new XElement("Name", this.FirstName)) //and so on...
}

然后将字符串解码为用户:

static User GetUserFromXElement(string xml)
{
    XElement temp = XElement.Parse(xml);
    User temp = new User();
    foreach (XElement inner in temp.Elements())
    {
        switch inner.Name
        {
            case "Name":
                temp.Name = inner.Value
                break;
            //whatever
        }
    }
}

然后这样做:

public string UsersToElements (List<Users> toWrite)
{
    Stringbuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    XElement root = new XElement("root");
    XDocument temp = new XDocument(root);
    foreach (User user in toWrite)
    {
        root.Append(user.GetXElement());
    }
    temp.Save(sw);
    return sw.ToString();
}

和此:

public List<Users> ElementsToUsers (string xml)
{
    List<Users> usrsList = new List<Users>();
    XDocument temp = XDocument.Load(xml);
    foreach (XElement e in XDocument.Root.Elements())
    {
        usrsList.Append(Users.GetUserFromXElement(e));
    }
    return usrsList;
}

JSON解决方案(使用JSON.NET)

public JObject GetJObject()
{
return new JObject("user", new JProperty("name", this.FirstName)); //so on
}

static User GetUserFromJObject(string json)
{
JObject obj = JObject.Parse(json);
return new User() { FirstName = (string)obj["user"]["name"] }; //so on
}

public string UsersToElements (List<Users> users)
{    
   JObject root = new JObject(from usr in users select new JAttribute("user", usr.GetJObject());
   return root.ToString();
}

public List<users> ElementsToUsers(string json)
{
List<Users> users = new List<Users>();
JObject temp = JObject.Parse(json);
foreach (JObject o in (JEnumerable<JObject>)temp.Children())
{
users.Add(Users.GetUserFromJObject(o.ToString());
}
return users;
}

我不知道它是否有效:/(我所知道的XML确实如此,对JSON不太确定)

答案 3 :(得分:0)

使用此代码

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

var Array = combindedString.Split( new [] {','} );