Reputation: 255
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:
Required Output:
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
Upvotes: 1
Views: 2006
Reputation: 1649
I presumne that the data structure is like this:
class Data
{
public int cas {get;set;
public string pref {get;set;}
}
and some record:
List<Data> records;
because you said C# and LINQ, it has to be that way:).
From there it is simple:
List<Data> newRecords =
records
.GrouBy(data => data.cas)
.Select(gData => gData
.OrderBy(x => x?.pref?.Length ?? 0)
.LastOrDefault())
.Where(data => data != null)
.ToList()
;
Upvotes: 1
Reputation: 345
You can order all your data from the table descending by the length of the Pref property, group them by Cas value and then get only the first element from each group.
var result = from p in table
orderby p.Pref.Length descending
group p by p.Cas into g
select g.First();
Upvotes: 0
Reputation: 2453
var results = from p in tablename
group p by p.cas into g
order by g.Key
select new { cas = g.Key, maximum =
g.First(r => r.pref.Length == g.Max(y => y.pref.Length)) };
Upvotes: 0
Reputation: 8659
This should work:
var results = yourTable.GroupBy(x => x.cas).Select(g => g.OrderByDescending(og => og.pref.Length).First());
Upvotes: 1
Reputation: 66
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()
Upvotes: 1