Reputation: 51
I am trying to get last name using linq in visual studio. In my database, i have the Field name like "FullName".
In this Field I have value like "Subbu Cargos" I Wanna Display the "Cargos" in my textbox.
How can i make a simple linq query?
Upvotes: 0
Views: 749
Reputation: 31249
You could also do it like this:
customers
.Select (b => b.FullName.Substring ((b.FullName.IndexOf(' ') + 1)));
Upvotes: 0
Reputation: 5819
I would suggest not trying to parse out the last name. Like you say, first and last names could be switched around, someone might have a second name, or a last name that consists of multiple words (“van Dijk”), or may not have entered a last name at all.
Check out this article: Falsehoods Programmers Believe About Names
If you still want to do this however, try something like this:
customers.Select(c => c.FullName.Split(' ').Last());
You might not be able to this on the server side. In that case:
customers
.Select(c => c.FullName)
.ToList()
.Select(n => n.Split(' ').Last());
Untested, but this should give a rough idea.
Upvotes: 0
Reputation: 883
I would suggest breaking it up into different fields - Firstname, Middlename, lastname, Title - and rebuilding the name on the fly when you come to display it.
If you're still determined to use one field, then consider a query like:
string s = "Subba Cargos";
var lastnames = from name in s.Split(new Char[] { ' ' }).Last<string>()
select name;
Upvotes: 0
Reputation: 18961
Would it be over simple to say:
return FullName.Split(' ').Last()
?
Upvotes: 1