-2

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;
}
Sensei James
  • 2,617
  • 30
  • 36

6 Answers6

1

You can do this:

var roles=System.Enum.GetValues(typeof(QARoles));
return roles.Where(r=>user.Roles.Any(role=>role.Name.Equals(r.ToString())).ToList();
ocuenca
  • 38,548
  • 11
  • 89
  • 102
1

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();
decPL
  • 5,384
  • 1
  • 26
  • 36
0
return (from role in user.Roles 
        from QARoles qarole in System.Enum.GetValues(typeof(QARoles))
        where role.Name.Equals(qarole.ToString()) 
        select qarole)
.ToList();

or

 return user.Roles.SelectMany(role => System.Enum.GetValues(typeof(QARoles)).Cast<QARoles>(),
            (role, qarole) => new {role, qarole})
         .Where(t => t.role.Name.Equals(t.qarole.ToString())).Select(t => t.qarole).ToList();
stuartd
  • 70,509
  • 14
  • 132
  • 163
0

using ReSharper:

            return (from role in user.Roles
                from QARoles qarole 
                in System.Enum.GetValues(typeof(QARoles))
                where role.Name.Equals(qarole.ToString())
                select qarole)
                .ToList();
Malte R
  • 468
  • 5
  • 16
0
return System.Enum.GetValues(typeof(QARoles)).Where(role => 
user.Roles.Any(r => r.Name == role.ToString()))
Ashley John
  • 2,379
  • 2
  • 21
  • 36
0

I came up with this myself:

    return user.Roles
        .Select(r => r.Name).ToList<string>()
        .Select(str =>
        {
            QARoles qarole;
            bool success = System.Enum.TryParse(str, out qarole);
            return new { qarole, success };
        })
        .Where(pair => pair.success)
        .Select(pair => pair.qarole)
        .ToList();

But I dont think it has become better readable ;-)

  • Started writing a comment on how you could slightly improve on that - but realized it can be written in a much simpler way - check my answer. – decPL Oct 11 '16 at 14:31