Solved

Get Longest String in a Database column using LinqToSQL

Posted on 2014-02-08
18
400 Views
Last Modified: 2016-02-10
I need to find and return the longest string in a database column only through Linq and VB.net
0
Comment
Question by:Dodsworth
  • 7
  • 4
  • 3
  • +3
18 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 39844024
0
 
LVL 1

Author Comment

by:Dodsworth
ID: 39844050
Yes I know. It's flagged for deletion as the first guy to answer couldn't help.  I thought a fresh question might get more attention !
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39844090
In your other question you asked, "Where do I put my column name?" Do you know how to set up your data classes to be LINQ-to-SQL enabled?
0
 
LVL 1

Author Comment

by:Dodsworth
ID: 39844108
Yes.
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
ID: 39844197
You can use a Group By expression along with an Order By to determine this information. For example:

Dim query = From cust In ctx.GetTable(Of Customer)()
            Group cust By cust.LastName Into Group
            Order By Group.Max(Function(c) c.LastName.Length) Descending
            Select LastName

Console.WriteLine(query.First())  ' Since you have an enumerable of last
                                  '  names resulting from the query, just
                                  '  take the top item since we ordered
                                  '  by descending in the query

Open in new window


If you're curious, the LINQ gets turned into this SQL:

SELECT [t1].[last_name]
FROM (
      SELECT MAX(LEN([t0].[last_name])) AS [value],
             [t0].[last_name]
      FROM [Customer] AS [t0]
      GROUP BY [t0].[last_name]
     ) AS [t1]
ORDER BY [t1].[value] DESC

Open in new window

0
 
LVL 1

Author Comment

by:Dodsworth
ID: 39844248
Can you confirm the changes that I've made please ?  The Table is called Catalog and the column is ItemName.  But .first returns Nothing.

Dim query = From cat In dc.GetTable(Of Catalog)()
            Group cat By cat.ItemName Into Group
            Order By Group.Max(Function(c) c.ItemName.Length) Descending
            Select ItemName
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39844251
Looks to be accurate. Is the column that you are working with nullable?

*edit

I don't think it should matter (my testing seems to agree).

If it's of any use, here's my setup:

Screenshot
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39844577
Hi Dodsworth;

The following query should result in what you need. In the below query the first FirstOrDefault takes the first record in the group and the second FirstOrDefault just returns the value from the first group. Now there may be more then one value in the group with different names but the same length, this code is just picking the first in the group.
             
Dim query = (From cat In dc.GetTable(Of Catalog)()
             Group cat By Key = cat.ItemName.Length Into Group
             Order By Key Descending
             Select Group.Select(Function(c) c.ItemName).FirstOrDefault()
             ).FirstOrDefault()

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 1

Author Comment

by:Dodsworth
ID: 39846729
Hmm.  I'm getting Nothing back from yours too Fernando.

Any ideas why?
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 250 total points
ID: 39847312
Are you getting an exception? If so please post exception message and inner exception message here.

Is there any records in the database?

If you have a test database can you zip it up into a zip file and post it so we can download it to test with.
0
 
LVL 1

Author Comment

by:Dodsworth
ID: 39848016
no exception and yes records are there.  

Is there a way to break down the query to see where it's going wrong.

Sorry but Linq is a complete misqery to me :)
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39848639
You can break the LINQ up, but unfortunately, due to the way LINQ works, you won't be able to see anything until you actually execute the query--just defining the query doesn't actually execute it.

If you run the SQL that LINQ generates directly on the database, do you get records back? If you do (where [query] is the variable you assign the query to):

?[query].ToString()

Open in new window


...in the Immediate Window during debugging, you can get a copy of the generated SQL.
0
 
LVL 1

Author Comment

by:Dodsworth
ID: 39865192
Well I have no idea why both your efforts returned Nothing so I had a go myself on a different table and came up with this..

Dim l = From lu In dc.LookUp Select lu.LookUpText.Length Order By Length Descending.FirstOrDefault

Open in new window


Which worked.  So I copied the working code into this window but thought it would be clearer if I altered it to match the original table and column names.

Dim query = From cat In dc.Catalog Select cat.ItemName.Length Order By Length Descending.FirstOrDefault

Open in new window


I tested the new version against Catalog and it gave an error !?

It runs fine without the .FirstOrDefault and returns rows.

Very confused :(

Ideas please?
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 39883908
What id you add parenthesis?

Dim query = (From cat In dc.Catalog Select cat.ItemName.Length Order By Length Descending).FirstOrDefault

Open in new window

0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39883922
Hi Dodsworth;

If you can create a small test project which exhibits the same issue and zip that complete project up along with a test database file with test data in it I will take a look at it.

Please note DO NOT ATTEMPT TO UPLOAD TO EE it will not allow certain file types and therefore will not allow you to upload them. Something like  Microsoft SkyDrive or some other web site. Make sure it is in a publicly accessible folder.
0
 
LVL 27

Expert Comment

by:MikeToole
ID: 39884006
This uses the Fluent interface (I find it more straightforward) to get the Employee with the longest address:

Employees.OrderByDescending(Function(e) e.Address.Length).FirstOrDefault()

Open in new window


LINQPad4 shows the generated SQL as;

SELECT TOP (1) [t0].[EmployeeID], [t0].[LastName], [t0].[FirstName], [t0].[Title], [t0].[TitleOfCourtesy], [t0].[BirthDate], [t0].[HireDate], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[HomePhone], [t0].[Extension], [t0].[Photo], [t0].[Notes], [t0].[ReportsTo], [t0].[PhotoPath]
FROM [Employees] AS [t0]
ORDER BY LEN([t0].[Address]) DESC

Open in new window


Hope this helps
0
 
LVL 1

Author Comment

by:Dodsworth
ID: 39885264
Oops... Major fail !  When Fernando asked if there were records in the database, I confirmed this by doing a record count.  The reason the Catalog query failed was that, although there were records, their was no data in the ItemName column. Doh!
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now