LINQ to SQL - Split and re-join full name RRS feed

  • Question

  • Hello,
    I am trying to pull records from a Users table and push them into a gridview.  The User's names are in one column: FullName.  The problem is that I need to order the gridview by last name.
    What I think I want to do is split the FullName and rejoin.  I have tried the LET keyword, but am getting an ArrayIndex error.

    Here's a sample of what I am trying to split:
    George Washington >> will be >> Washington, George
    Francis Scott Key >> will be >> Scott Key, Francis

    Here's about as far as I got and it doesn't work...

                var qry = from u in Users 
                          let arr = u.FullName.Split(' ').ToArray() 
                          select new 
                              UserId = u.UserId, 
                              FullName = arr[1] + ", " + arr[0] 

    Wednesday, February 11, 2009 10:00 PM

All replies

  • The problem here is how you will know which parts are the forename and which the surname. e.g. in your second example how do you know that Scott is his surname and not part of his forename or a middle name?

    If you're happy to accept that limitation one option would be to create fake Surname and Forename properties on the object and have each of those pull the part it needs from FullName.  For the gridview to be able to sort or select however you'd have to make sure you pull the data back from the SQL and then process these elements on the client - e.g. go through ToList() first.

    Friday, March 6, 2009 9:40 PM