Reputation: 274
I am playing with lists to better understand them. Can I output a specific class variable to a List selection to compact the following code?
Here is what I think should be possible (DB.OperationsTeam.(choose just the UserEmail variable from POPSUser class))
private string OperationsMembers
{
get
{
List<POPSUser> UniqueList = DB.OperationsTeam.UserEmail.Distinct().ToList();
return string.Join(";", UniqueList);
}
}
Expected output: [email protected]; [email protected]; [email protected]
Here is current working code, but don't think I need to create another List and loop with a foreach. I used Distinct() because some users would be in multiple departments within the database query.
private string OperationsMembers
{
get
{
List<string> EmailAddressList = new List<string>();
foreach (POPSUser user in DB.OperationsTeam)
{
EmailAddressList.Add(user.UserEmail);
}
if (EmailAddressList.Count > 0)
{
List<string> UniqueList = EmailAddressList.Distinct().ToList();
return string.Join(";", UniqueList);
}
else { return ""; }
}
}
DB.OperationsTeam is a POPSUser List with UserID, UserName, UserEmail etc.
** UPDATE AFTER HELPFUL COMMENTS (didn't know where else to post helpful answer) * Nice, clean, and compact, thanks all!
private string OperationsMembers
{
get
{
return string.Join(";", DB.OperationsTeam.Select(u => u.UserEmail).Distinct());
}
}
Upvotes: 1
Views: 195
Reputation: 236238
I think you should project your POPSUser
entity to email string. Use Select operator for projection:
DB.OperationsTeam.Select(u => u.UserEmail).Distinct();
Side note: your current working solution will load whole user data from database (i.e. name, email, id, etc) and instantiate user instances when you will enumerate over OperationsTeam set. But when you do projection as above, it will occur on server side and that will generate SQL which loads only required fields:
SELECT DISTINCT
[Extent1].[UserEmail] AS [UserEmail]
FROM [dbo].[OperationsTeam] AS [Extent1]
Upvotes: 4
Reputation: 152566
The problem is that .Distinct()
will return "distinct" POPSUser
instances which may not be what you want. If you want distinct emails, just insert a Select
to extract the email value:
var UniqueList = DB.OperationsTeam
.Select(u => u.UserEmail)
.Distinct()
.ToList();
return string.Join(";", UniqueList);
Also note that ToList
is not necessary since string.Join
will accept an IEnumerable<string>
.
Upvotes: 2