Solved

Get Longest String in a Database column using LinqToSQL

Posted on 2014-02-08
18
405 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

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

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.

828 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