Manjit Singh Manjit Singh - 1 year ago 173
C# Question

How to get only the max string length column row from a table using linq?

I have a table like the following image with two column "cas" and "pref" and you can see there are common values in "cas" column so i want to group by "cas" and fetch only the rows those have max string length in the "pref" column using the Linq in c#.

Input Table:

enter image description here

Required Output:

enter image description here

I am using following query to get the upper required output in sql but how to do it by LINQ?

select cas, (select top 1 pref from pdf_tab b where b.cas = a.cas order by LEN(pref) desc )
from pdf_tab a group by cas

Answer Source

This will return longest element from each group:

      var results = from p in tablename
      group p by p.cas into g
      select g.OrderByDescending(e=>e.pref.Length).First()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download