简体   繁体   中英

Parse full name into First Name and Last Name from SQL Server - Linq to Entities

I have a C# console application which simply pulls information from a Sql Server 2008 database and outputs it to an excel sheet.

I am using Linq to Entities.

Here is a snippet of the code just to demonstrate how I output the data from the database to the excel sheet.

cell = dataRow.CreateCell(colPosition++); // Title Group ID
cell.SetCellValue(currentTitle.TitleGroupID);

My issue is, that in my database, the Users name is stored as his/her full name, eg "John Smith", however, in the excel sheet this is separated into First Name and Last Name.

Is there a way to parse the users name into First Name and Last Name?

Thanks in advance, if more info is needed, just ask :)

if you are sure the first name doesn't contain any spaces you can use the string.Split method

string [] Name = fullNameString.Split(" ");
string firstname = Name[0];
string lastname = Name[1];

The thing is with name is that they are complicated. So for short, no you can't do that since it is basically impossible to know what is a last name and first name from a full name. But you can go with the assumptions that the last part is always the last name (even though that is not the case in many situations) and split the string on space.

string [] Name = fullNameString.Split(" ");
string firstname = string.Join(" ", Name.Take(Name.Length - 1));
string lastname = Name.Last();

您可以将字符串按空格分隔,然后将第一个单词作为名字,将其余单词作为姓氏。

You can use the naive approach of simply splitting the last word off.

However this isn't something that can be reliably solved without knowing more about language. "Fred Di Costello" actually has the lastname "Di Costello", same with "Kraus Von Trappe".

it is very difficult task. You should to analyze all your data. for simple case you can split text by " " and first name set first word, last name set second world. But if you have other case you should resolve it with other way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM