简体   繁体   中英

How to get first character from firstName and lastName from Database and assign to object?

I am new to this. I am getting data from database and storing each tuple in the following way to form a list:

var dataFromDB = (
    from to in _context.Time
    join user in _context.Users
    on to.UserId equals user.Id
    select new Events
    {
        userId = user.Id,
        title = user.FirstName[0] + " " + user.LastName[0],
        ...
    }).ToList();

I want title to have the initials from FirstName and LastName where FirstName and LastName are coming from the Users table. Example, if the FirstName is John and LastName is Doe , then I want title to have JD .

Events class is in the following way:

public class CalendarEvents
{
    public string userId { get; set; }
    public string title { get; set; }               
    ...
}

Edit 1.0

On running the code, I am getting the following exception:

An exception of type 'System.ArgumentNullException' occurred in mscorlib.dll but was not handled in user code.

Additional information: Value cannot be null.

Edit 2.0

FirstName and LastName is in the following way:

[Required(ErrorMessage = "Please enter first name")]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[Required(ErrorMessage = "Please enter last name")]
[Display(Name = "Last Name")]
public string LastName { get; set; }

If you want the first initial and second initial I would suggest:

title = user.FirstName.FirstOrDefault().ToString()
    + user.LastName.FirstOrDefault().ToString(),

Since, user.FirstName.FirstOrDefault() returns the first character from the FirstName .

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