Dave Stockinger
Dave Stockinger

Reputation: 139

LINQ get last position of special char

i have a simple LINQ Query (linq to entities via EF)

var QueueList = (from q in context.queues                                        
                 select new { 
                             Qid = q.id, 
                             Qname = q.name.Substring(q.name.IndexOf(":") + 2) 
                 }).ToList();

The problem i have is the Qname. The name in the Database normally looks like this:

Company::QueueName

but now i have a few new Queues where the name looks like this:

Company::Group::QueueName

so i don't need to find the first ":" in the string but the last.

SQL doesn't support the "LastIndexOf()" method. So how do i get the last ":" in the QueueName?

I've tried it with "Reverse()" but the result was a little bit wrong (gnirts instead of string).

Upvotes: 1

Views: 2028

Answers (1)

James S
James S

Reputation: 3588

If I were you I'd give up trying to use functions that translate to Sql string functions for your string manipulation.

Instead just select the full string and translate it post retrieval.

ie:

var QueueList = (from q in context.queues                                        
                 select new { 
                             Qid = q.id, 
                             Qname = q.name 
                 }).ToList()
    .Select(x => new {
         Qid = x.Qid, 
         Qname = x.Qname.Substring(x.Qname.LastIndexOf(":") + 1) 
    });

moving the Substring/LastIndexOf functions to past the ToList() means they are just the .Net native functions acting on a string that has already been retrieved, rather than having to be translated to SQL functions acting on the database.

Upvotes: 5

Related Questions