2

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

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

Name, LastName, DateOfBirth //多维数组??

现在我想将此列表存储为字符串,并且我希望能够重用它,即

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

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

是否可以?

4

4 回答 4

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 [] {','} );
于 2013-02-16T17:03:32.573 回答
3

如果您有很多用户和很多列,最好编写自己的自定义转换器类。

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 构建您的用户字符串,您将在性能方面获胜。您还可以轻松扩展转换器以考虑不同的分隔符/附加逻辑等。

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

于 2013-02-16T17:34:55.573 回答
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 不太确定)

于 2013-02-16T17:51:42.857 回答
0

使用此代码

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

var Array = combindedString.Split( new [] {','} );
于 2013-02-16T17:25:59.947 回答