C# - Seperate last name, first name in string that's seperated by comma

Viewed 1471

I have an ASP.NET Core 3.1 Console Application that is reading an OFAC csv file that is "|" delimitted. The database table has a FirstName and LastName field that will hold the first and last name of these individuals. The problem is that the OFAC file has the full name in one string such as "last name, first name". I am able to read the file correctly, but I just want to be able to store the last name and first name in seperate properties so I can update them into our database as such.

Note: Alot of these names have two words for their last names and two words for the first name, and some do not.

Another Note: You can find OFAC file from https://www.treasury.gov/ofac/downloads/sdn.pip by clicking this link to get a better understanding of the file format I am parsing.

Example names from OFAC file:

"CRUZ, Juan M. de la"

"ESCOBAR BUITRAGO, Walter"

"GALINDO, Gilmer Antonio"

"GOMEZ BERRIO, Olmes de Jesus"

What I am trying to accomplish:

I want to seperate this string to have whatever is before the comma to be stored into the LastName field, and everything after the comma to be stored into FirstName field.

What I have tried:

I get this value "CRUZ, Juan M. de la" when reading the full name as such:

FullName = fields[1],

However, when I try to do a split on the comma for the name I get this result System.String[] as such:

LastName = fields[1].Split(',').ToString(),

Can anyone help me seperating any word(s) before the ',' and assign it to the LastName field, and every word(s) after the comma be assigned to my FirstName field regardless of how many names they have in their first or last name.

3 Answers

You are splitting into an array, but then not indexing which element of the array to use for each field.

var nameParts = fields[1].Split(',');
var lastName = nameParts[0];
var firstName = nameParts.Length > 1 ? nameParts[1] : string.Empty;

Additionaly you may want to handle cases where there are more than one comma in the string and replacing with a space.

var firstName = nameParts.Length > 1 ? string.Join(" ", nameParts.Skip(1)) : string.Empty;

Another way

  static string ReverseName(string name)
    {
        return string.Join(",", name.Split(",").Reverse()).ToString();
    }

I am unsure if I understood correctly, but it's quite trivial as

string fullname = "CRUZ, Juan M. de la" ; // == fields[1]
string lastname = fullname.Split(',')[0];
string firstname = fullname.Split(',')[1];
Related