h3x3n95
h3x3n95

Reputation: 37

Using linq to separate strings where the special character is

I've got a foreach loop that iterates through rows in an sql table. One of the columns, named 'UserName', lists users and their location separated by '#'.

Example:

Id UserName
1 Room1 # John Smith
2 Room2 # Jane Doe

I'm trying to get the location and the name into separate variables while excluding the #. I'm certain this can be done with linq, but I'm having no success.

Any Help would be appreciated. Thanks

Upvotes: 1

Views: 581

Answers (1)

Anton Kovachev
Anton Kovachev

Reputation: 337

If you are using Entity Framework it could be something like this

public Users
{
   public int Id { get; set; }
   public string UserName { get; set; }
}

public UserViewModel 
{
   public string Room {get; set;}
   public string Name {get; set;}
}

var users = dbContext.Users.Select(user => new UserViewModel {
   Room = user.UserName.Split(new char[] { '#' }).First(),
   Name = user.UserName.Split(new char[] { '#' }).Last()
}).ToLIst();

Upvotes: 1

Related Questions