Nuzheen Kazim
Nuzheen Kazim

Reputation: 35

how to remove a character at the end of a string in linq c#

I have the following LINQ query; I want to remove dot character if available at the end of string

var hatoList = (from L in db.vHatoList select L.HatoFullName.Trim('.')).ToList();

Upvotes: 0

Views: 1274

Answers (2)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9903

You are using linq to sql and database does not understand TrimEnd or Trim.

So first you have need to load data in memory and then use TrimEnd method.

var hatoList = (from L in db.vHatoList select L.HatoFullName).ToList().
             Select(t=>t.TrimEnd('.'));

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500865

You're currently trying to perform the query in the database. We don't know what database technology you're using, so it's hard to know whether there's some way to make it actually happen in the database, but it's probably simplest to do in memory instead (given that it won't change how many records will be returned). The AsEnumerable() method is used to just change the compile-time type to IEnumerable<T> (instead of IQueryable<T>) forcing the rest of the query to be evaluated in .NET code instead of in the database:

var hatoList = db.vHatoList 
                 .AsEnumerable()
                 .Select(entry => entry.HatoFullName.TrimEnd('.'))
                 .ToList();

(I've also changed the call from Trim to TrimEnd to avoid it removing periods at the start of the string.)

Upvotes: 1

Related Questions