简体   繁体   中英

Linq group by collection with where

I have these structures: Ticket has a lot of CustomFormFieldItemsInTicket. The relationship is one to many.

And I want to create linq which group ticket by CustomFormFieldItemsInTicket but I want to set which items from the collection will be used.

In sql it is something like this:

  SELECT COUNT(*)
  FROM [beta4].[dbo].[Tickets] as t
  INNER JOIN [beta4].[dbo].[CustomFormFieldsInTickets] as cfit
  ON cfit.TicketId = t.Id
  WHERE cfit.CustomFormFieldId = 5 // I set the value
  GROUP by cfit.SelectedCustomFormFieldItemId

I tried something like this. But did not work for me.

query.GroupBy(gr => gr.ticket.CustomFormFieldsInTicket.Where(wh => wh.CustomFormFieldId == 5).Select(sl => sl.SelectedCustomFormFieldItemId));

Not tested, but something like this.

var query = (from t in gr.Tickets
        join cfit in gr.CustomForm on t.id equals cfit.TicketId
        where cfit.CustomFromFieldId == 5
        group cfit.field by cfit.SelectedCustomFormFieldItemId into g
        select g).ToList() or .Count();

Get familiar with using Linq like this. Sometimes using linq like this is useful, sometimes it is not.

Next time though, search a bit more, there are countless topics on this and msdn pages, for example:

Stackoverflow - Group By Linq

MSDN examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM