如何将对象转换为字符串列表?

时间:2014-08-25 04:10:43

标签: c# linq list

我希望通过使用linq select query获取两个值,并尝试将对象转换为字符串列表。 我想将list<object>转换为list<string>。 代码如下。 我将对象转换为字符串列表时出错: return returnvalue =(List)userlist;

public List<string> GetUserList(string username)
{
    List<User> UserList = new List<User>();
    List<string> returnvalue = new List<string>();
    try
    {
        string returnstring = string.Empty;
        DataTable dt = Library.Helper.FindUser(username, 200);
        foreach (DataRow dr in dt.Rows)
        {
            User user = new User();
            spuser.id = dr["ID"].ToString();
            spuser.name = dr["Name"].ToString();
            UserList.Add(user);
        }
    }
    catch (Exception ex)
    {
    }

    List<SharePointMentoinUser> userlist = UserList.Select(a => new User { name = (string)a.name, id = (string)a.id }).ToList();

    **return returnvalue = (List<string>)userlist;**
}

2 个答案:

答案 0 :(得分:2)

选择为数组,然后使用SelectMany

return Userlist
     .Select(u => new []{ u.name.ToString(), u.id.ToString() })
     .SelectMany(u => u)
     .ToList();

这将返回一个列表,其中包含UserList中所有用户的用户名和ID。

答案 1 :(得分:1)

        List<User> UserList = new List<User>();
        User usr = new User();
        usr.id = "1";
        usr.name = "name1";

        User usr2 = new User();
        usr2.id = "2";
        usr2.name = "name2";

        UserList.Add(usr);
        UserList.Add(usr2);
        List<string> userlist = UserList.Select(a => a.id.ToString() +","+ a.name.ToString()).ToList();

        foreach (string str in userlist)
        {
            Console.WriteLine(str);

        }