linq sort many 2 many question
My main entity is called [Contract]. Contract has a many 2 many relationship w/ [Service].
When I query for a list of Contracts I grab the 1st Service available like this:
IQueryable<Contract> q = ctx.Contracts.Skip(startRow - 1).Take(pgSize);
q.Select(c =>
new ContractSearchResult()
{
ContractID = c.ContractID,
FirstService = c.Contract2Service.FirstOrDefault().Service.Name,
ServiceCount = c.Contract2Service.Count,
}
).ToList();
(When I display this list I show the FirstService if there's only 1. If > 1 I show "My1stService (3)" to show I'm seeing the 1st of 3 services)开发者_C百科 This works fine.
My question is this:
Is there any way to sort by FirstService? Or is this impossible? I haven't found a way of expressing this in linq and allow for paging.
Any help would be appreciated.
You need to OrderBy before you page.
var result = ctx.Contracts
.Select(c =>
new ContractSearchResult()
{
ContractID = c.ContractID,
FirstService = c.Contract2Service.FirstOrDefault().Service.Name,
ServiceCount = c.Contract2Service.Count,
})
.OrderBy(x => x.FirstService)
.Skip(startRow - 1)
.Take(pgSize)
.ToList();
Also note that FirstOrDefault
can return null
and you should check for that. If you know that it will (or should) never be null
then use First
instead.
q.OrderBy(c => c.Contract2Service.FirstOrDefault().Service.Name)
.Select(c =>
new ContractSearchResult()
{
ContractID = c.ContractID,
FirstService = c.Contract2Service.FirstOrDefault().Service.Name,
ServiceCount = c.Contract2Service.Count,
}
)
.ToList();
Unless I'm missing something in your question (which is possible), it should be as simple as calling OrderBy()
after your call to Select()
精彩评论