tags:

views:

411

answers:

1

Hi I would like to convert a list of User's properties into strings array (for json receiver) like:

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

var jsonData = (
   from user in users
   select new { user.Id, user.Person.Lastname, user.Person.Firstname });

return Json(jsonData)

The result is an array named fields

[{"Id":1,"Lastname":"Doe","Firstname":"John"},{"Id":2,"Lastname":"Smith","Firstname":"Adam"},...]

but I would like it to be the array of arrays of plain strings like:

[["1","Doe","John"]
 ["2","Smith","Adam"], ...]

How to cast linq result to strings array?

+6  A: 
var jsonData = from user in users
               select new[] { user.Id.ToString(),
                              user.Person.Lastname,
                              user.Person.Firstname };

Alternatively, you can use the lambda syntax:

var jsonData = users.Select(user => new[] { user.Id.ToString(),
                                            user.Person.Lastname,
                                            user.Person.Firstname });
Mehrdad Afshari
thanks, both your proposals work well :)Anyway, I was trying such a strings array cast before, but finished with some strange index errors. Same was with your code, then I realized that my data source were returning IQueryable object which was the problem - users.ToList() solved this.Anyway, your answer was helpful to get this. Thanks.
twk
FYI, this exact solution didn't work for me since I had numeric types mixed in. (I got an error saying that the compiler couldn't determine the type of the array.) But I used "new object[]" and this solved my problem.
Mike
@Mike: Yes, that's exactly why I've called `.ToString()` on `user.Id` which I assumed to be an integer. For `new[]` to work, the compiler should be able to infer the type of the array from the objects passed to it. If their types are not compatible, the compiler is going to complain.
Mehrdad Afshari
@Mehrdad, good point; I missed that. In my case, I had to pass the data into a DataSet, and I wanted it in its original format (not a string). So I just wanted to make sure people were aware that "select new object[] { ... }" was an option.
Mike