What I'm trying to solve for:
Cycle through a List that I have where:
- If the list contains duplicate entries of "CompanyName", then grab the "UserEmail" properties for each user that belongs to the same "CompanyName" and append the email addresses together as One record for the Company (in a separate list object), so that the resulting List that I make would look equivalent to:
myList[0].CompanyName = "Company1" // Company1 is found in two separate records in my original List object.
myList[0].UserEmails = "[email protected];[email protected]"
The model for my current List looks like:
- CompanyName
- UserEmail
- UserPersonas (Looking for only users with a specific "Admin" string listed in their account properties)
The model for the resulting List should look like:
- CompanyName
- UserEmails
I'm querying an external program, getting all company names that have a UserPersonas that contains "Admin" (among their other entries) into one List object.
One company can have several users that have a "UserPersonas" that contains "Admin", so I want to only have one record per company with the semicolon appended email addresses as an entry in that CompanyName's record (as its own List object.)
Can I use another LINQ transaction to accomplish what I'm going for?
Below is a screenshot of what my current output from my List object looks like
var getDupes = bUsers.GroupBy(t => new { t.CompanyName, t.UserEmail }).ToList();
CodePudding user response:
I'm not sure it 'll give you an explanation how it works internally, but nevertheless... Assuming we have a class
public class SomeClass
{
public string CompanyName { get; set; }
public string UserEmails { get; set; }
}
we can do the next grouping and combining:
var result = list.GroupBy(e => e.CompanyName)
.Select(e => new SomeClass
{
CompanyName = e.Key,
UserEmails = string.Join("; ", e.Select(e => e.UserEmail).ToList())
});