Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 424
  • Last Modified:

Get Longest String in a Database column using LinqToSQL

I need to find and return the longest string in a database column only through Linq and VB.net
0
Dodsworth
Asked:
Dodsworth
  • 7
  • 4
  • 3
  • +3
2 Solutions
 
AndyAinscowCommented:
0
 
DodsworthAuthor Commented:
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
 
käµfm³d 👽Commented:
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
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

 
DodsworthAuthor Commented:
Yes.
0
 
käµfm³d 👽Commented:
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
 
DodsworthAuthor Commented:
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
 
käµfm³d 👽Commented:
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
 
Fernando SotoCommented:
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
 
DodsworthAuthor Commented:
Hmm.  I'm getting Nothing back from yours too Fernando.

Any ideas why?
0
 
Fernando SotoCommented:
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
 
DodsworthAuthor Commented:
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
 
käµfm³d 👽Commented:
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
 
DodsworthAuthor Commented:
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
 
Ioannis ParaskevopoulosCommented:
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
 
Fernando SotoCommented:
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
 
MikeTooleCommented:
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
 
DodsworthAuthor Commented:
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

Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

  • 7
  • 4
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now