Solved

Get Longest String in a Database column using LinqToSQL

Posted on 2014-02-08
18
396 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 74

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 74

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 74

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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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 74

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

705 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

19 Experts available now in Live!

Get 1:1 Help Now