Solved

Get Longest String in a Database column using LinqToSQL

Posted on 2014-02-08
18
412 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
How To Reduce Deployment Times With Pre-Baked AMIs

Even if we can't include all the files in the base image, we can sometimes include some of the larger files that we would otherwise have to download, and we can also sometimes remove the most time-consuming steps. This can help a lot with reducing deployment times.

 
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 63

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
 
LVL 1

Author Comment

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

Any ideas why?
0
 
LVL 63

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 63

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

Understanding Linux Permissions

Linux for beginners: How to view the permissions associated with files and directories and also how you can change them.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

623 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