Nico Walsemann
Nico Walsemann

Reputation: 190

LINQ Grouping to same recipient

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

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..

Upvotes: 1

Views: 67

Answers (2)

Ortiga
Ortiga

Reputation: 8824

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.

Upvotes: 1

Quercus
Quercus

Reputation: 2065

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))

Upvotes: 2

Related Questions