0

I want to get two values by using linq select query and try to convert object to string list. I am trying to convert list<object> to list<string>. The code as below. I got the error when I convert object to string list : 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;**
}
1
  • I think your best option is to serialize the result if you need to pass string for some reason. Other than that - try to work on the other end so that it can accepts a List of User objects instead of strings and if that is also not possible, then maybe select single values, but it seems the less preferable scenario.
    – Leron
    Aug 25, 2014 at 4:20

2 Answers 2

2

Select as array then use SelectMany.

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

This will return a list that contains user's name and id for all users in UserList.

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

        }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.