|
-
Jul 8th, 2012, 04:13 PM
#1
Thread Starter
Hyperactive Member
[RESOLVED] LINQ for converting IList<Role> to string array of Role.Name
Hi,
The following work, but I'm pretty sure can be converted to a LINQ query, and been wasting time on it (Not necessary, but curiosity can be a killer sometimes)
(User got a member of type IList<Role> where Role have a member "RoleName")
Code:
public override string[] GetRolesForUser(string username)
{
var roles = new StringBuilder();
try
{
User user = UserRepository.GetUserByName(username, ApplicationName);
if (user != null)
{
foreach (Role role in user.Roles)
{
roles.Append(role.RoleName + ",");
}
}
}
catch (Exception ex)
{
throw new MemberAccessException("Error processing role data - " + ex.Message);
}
if (roles.Length > 0)
{
roles.Remove(roles.Length - 1, 1);
return roles.ToString().Split(',');
}
return new string[0];
}
Figured where I loop over the roles a query can do the job......no?
-
Jul 8th, 2012, 08:05 PM
#2
Re: LINQ for converting IList<Role> to string array of Role.Name
Take the IList<Role> and use the Select in a lambda where you retrieve the .RoleName.
Code:
string[] NameArray = RList.Select(r => r.RoleName).ToArray();
RList as the IList<Role>
Last edited by AceInfinity; Jul 8th, 2012 at 08:11 PM.
<<<------------
.NET Programming (2012 - 2018)
®Crestron - DMC-T Certified Programmer | Software Developer <<<------------
-
Jul 9th, 2012, 12:32 AM
#3
Thread Starter
Hyperactive Member
Re: LINQ for converting IList<Role> to string array of Role.Name
Awesome, thanks!
Did not test it yet, but much shorter / more readable:
Code:
public override string[] GetRolesForUser(string username)
{
try
{
User user = UserRepository.GetUserByName(username, ApplicationName);
if (user != null)
return user.Roles.Select(r => r.RoleName).ToArray();
}
catch (Exception ex)
{
throw new MemberAccessException("Error processing role data - " + ex.Message);
}
return new string[0];
}
-
Jul 9th, 2012, 01:50 AM
#4
Re: [RESOLVED] LINQ for converting IList<Role> to string array of Role.Name
Enjoy, hope it works for what you're trying to do here
<<<------------
.NET Programming (2012 - 2018)
®Crestron - DMC-T Certified Programmer | Software Developer <<<------------
-
Jul 9th, 2012, 01:53 AM
#5
Thread Starter
Hyperactive Member
Re: [RESOLVED] LINQ for converting IList<Role> to string array of Role.Name
 Originally Posted by AceInfinity
Enjoy, hope it works for what you're trying to do here 
Custom Membership and Role Providers using nHibernate.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|