douglaslps
douglaslps

Reputation: 8168

Selecting Consecutive String Entries with LINQ to Entities

At first you might think this is duplicate of this question but hopefully you will see it is not.

I also want to select groups of rows that are consecutive but consider that this time the entries are telephone numbers, therefore, stored as string.

I have been trying somethink like:

var numbers = await (from a in context.Telephones
                     from b in context.Telephones
                     Convert.ToInt32(a.Number) < Convert.ToInt32(b.Number) &&
                     Convert.ToInt32(b.Number) < (Convert.ToInt32(a.Number) + numberQuantity)
                     group b by new { a.Number }
                         into myGroup
                         where myGroup.Count() + 1 == numberQuantity
                         select myGroup.Key.Number).ToListAsync();

But this fails with:

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.

I understand that LINQ to Entities does not support Convert.ToInt32 but I am running out of ideas here to make it work.

So if my database has:

2063717608
2063717609
2063717610
2063717611
2063717613
2063717614

How can I select consecutive rows based on the string values? And when querying for 3 consecutive numbers get results like:

Upvotes: 1

Views: 285

Answers (1)

Alireza
Alireza

Reputation: 10476

1- If you are aware of performance side effect of calling AsEnumerable() cast your query and do conversion in memory on the retrieved entities.

2- If you don't want solution #1, you have to look for a way to solve the conversion problem:

2-1- Either change the column type in the database to int

2-2- Or select one of the solution previously proposed by other developers such as:

Problem with converting int to string in Linq to entities

Upvotes: 1

Related Questions