Home > Enterprise >  LINQ Grouping to same recipient
LINQ Grouping to same recipient

Time:09-17

i want to Group a List of Mails to their recipients.

The lstMails List is a List<MailModel>

MailModel has a Property which is string[] To.

for example there could be 5 mails in this List.

i would like to get a list for each Mail Recipient.

So for example

  • "lstNicoTest" = [ Mail1, Mail2 ]
  • "lstNicoJeff" = [ Mail3, Mail5 ]
  • "lstNicoFrank" = [ Mail2, Mail4 ]
  • "lstNicoStar" = [ Mail5 ]

at best it would be a ForEach(List<MailModel> list in lstMails.GroupBy(-----))

i dont know i have been googling around, but the problem is if i Group By it only checks if arrays are the Same, basicly if .To is ["reci1", "reci"] == ["reci1", "reci"] it doesnt not "copy" them basicly

if i did not provide sufficent information im sorry, im here to edit..

CodePudding user response:

You can fetch all recipients, then distinct them and then filter lstMails for the user.

Something like:

lstMails
  .SelectMany(mail => mail.To)
  .Distinct()
  .Select(user => lstMails.Where(mail => mail.To.Contains(user))

CodePudding user response:

I believe this gives the desired result:

var mailsByRecipient = (from m in lstMails
                  from recipient in m.To
                  select new { m, recipient } into s
                  group s by s.recipient into g
                  select new { recipient = g.Key, mails = g.Select(x => x.m) })
                  .ToList();

It returns a list of every unique email recipient, with the list of MailModels it's in.

It achieves that by first creating a cartesian product of each recipient with it's respective MailModel (into s), and uses that to group by recipient (into g).

The last select is purely aesthetical, creating a new object that contains the properties recipient and mails. I find it quirky to work with IGrouping<TKey, TElement> directly.

  • Related