Tony_KiloPapaMikeGolf Tony_KiloPapaMikeGolf - 1 month ago 23
C# Question

C# Linq Intersect

Most of the time I just use

foreach
statements, because that is a lot easier for me to code.
Later on, when my code is done, I convert the
foreach
into LINQ statements where it makes sense.

I want to learn how to write good readable LINQ statements.
How would you guys convert this
foreach
code into a correct LINQ statement ?

private List<QARoles> GetUserRoles(User user)
{
//TODO: Fix this with LINQ intersect.

var result = new List<QARoles>();
foreach (var role in user.Roles)
{
foreach (QARoles qarole in System.Enum.GetValues(typeof(QARoles)))
{
if (role.Name.Equals(qarole.ToString()))
{
result.Add(qarole);
}
}
}
return result;
}

Answer

This can be simplified to:

var result = user.Roles
                 .Where(r => Enum.IsDefined(typeof(QARoles), r.Name))
                 .Select(r => (QARoles)Enum.Parse(typeof(QARoles), r.Name))
                 .ToList();