Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

C# + Simple List to Array question

Posted on 2013-05-21
8
Medium Priority
?
232 Views
Last Modified: 2013-05-22
Hello all,

I have a List called List<Roles> and in this list there is the following columns:

RoleCode (string) - ie. ABC
ActionCreate (bool)  - ie. true
ActionUpdate (bool) - ie. true
ActionDelete (bool)  - ie. false
ActionAssign (bool)  - ie. false

What I want to do is populate a string array as follows:
Need to check if the action is true then create the string array such as using the ie. example.

ABC-Create, ABC-Update

So I want to append a dash between the rolecode and action stripping the word action for only those that are true.  Not sure Linq can be used in thie case.   Also was hoping to be able to keep it where if I added a new action later I would not have to hard code for it.

Thanks all.
0
Comment
Question by:sbornstein2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 39185786
Your question is not very clear.

As I understand you have a List where each item is an array of strings. Am I right?

What is not clear why you want to concatenate role code VALUE with action NAME, not value?

Could you please explain more clear?

What is <Roles> in the list definition?

What's on me, I'd create a class <Role> class with five fields as above. And you may add another field when you want. From an object you may retrieve all the information you need.
0
 

Author Comment

by:sbornstein2
ID: 39185796
No so I have a List already I need to convert it into a string array taking each of the action columns and appending it to the role code.  For example:

List<UserInRole> roles =
                UserInRoleService.FindAllUsersInRole().Where(p => p.UserID == GetCurrentUser().UserID
                                                             && p.IsActive).ToList();

   var arrRoles = new List<string>();

            foreach (UserInRole ur in roles)
            {

}

so I can get the values of the List item of course through the loop ur.RoleCode ur.ActionCreate etc.  I was hoping a cleaner way but  I could always say if(ur.ActionCreate) etc.  Maybe not really a cleaner way to do it
0
 

Author Comment

by:sbornstein2
ID: 39185801
I guess I could do this but was hoping to have a cleaner way.

            var arrRoles = new List<string>();

            foreach (UserInRole ur in roles)
            {
                if (ur.Role.ActionView)
                    arrRoles.Add(ur.Role.RoleCode + "-" + "View");

                if (ur.Role.ActionCreate)
                    arrRoles.Add(ur.Role.RoleCode + "-" + "Create");

                if (ur.Role.ActionUpdate)
                    arrRoles.Add(ur.Role.RoleCode + "-" + "Update");
            }
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:sbornstein2
ID: 39185805
I was wanting to be able to handle any Action column I guess but it is a property in the List.
0
 
LVL 30

Accepted Solution

by:
anarki_jimbel earned 840 total points
ID: 39185963
OK, I spent some time to write code to use reflection. I use my class Role as an example.

    public class Role
    {
        private string _RoleCode;
        private bool _ActionCreate;
        private bool _ActionUpdate;
        private bool _ActionDelete;
        private bool _ActionAssign;

        public string RoleCode
        {
            get { return _RoleCode; }
            set { _RoleCode = value; }
        }
        public bool ActionCreate
        {
            get { return _ActionCreate; }
            set { _ActionCreate = value; }
        }
        public bool ActionUpdate
        {
            get { return _ActionUpdate; }
            set { _ActionUpdate = value; }
        }
        public bool ActionDelete
        {
            get { return _ActionDelete; }
            set { _ActionDelete = value; }
        }
        public bool ActionAssign
        {
            get { return _ActionAssign; }
            set { _ActionAssign = value; }
        }

    }

Open in new window


Test code:

        private void button2_Click(object sender, EventArgs e)
        {
            List <Role> roles = new List<Role>();

            Role r1 = new Role();
            r1.RoleCode = "ABC";
            r1.ActionCreate = true;
            r1.ActionUpdate = true;
            r1.ActionDelete = false;
            r1.ActionAssign = false;
            Role r2 = new Role();
            r2.RoleCode = "DEF";
            r2.ActionCreate = false;
            r2.ActionUpdate = false;
            r2.ActionDelete = true;
            r2.ActionAssign = true;
            roles.Add(r1);
            roles.Add(r2);

            List<string> propertyNames = new List<string>();
            // get all public static properties of MyClass type
            PropertyInfo[] propertyInfos;
            propertyInfos = typeof(Role).GetProperties(BindingFlags.Public | BindingFlags.Instance);


            // write property names
            foreach(Role r in roles)
            {
                string name = (string)r.GetType().GetProperty("RoleCode").GetValue(r, null);
                List<string> values = new List<string>();
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    //System.Diagnostics.Debug.WriteLine(propertyInfo.Name);
                    if(propertyInfo.Name.StartsWith("Action"))
                    {
                        string nameWithoutAction = propertyInfo.Name.Substring(6);
                        bool value = (bool)r.GetType().GetProperty(propertyInfo.Name).GetValue(r,null);

                        if (value)
                        {
                            values.Add(name + "-" + nameWithoutAction);
                        }
                    }
                }

                foreach (string s in values)
                {
                    System.Diagnostics.Debug.WriteLine(s);
                    System.Diagnostics.Debug.WriteLine("======================");
                }
            }



        }

Open in new window



You will see output in output window of VS.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 39185969
Just remember - Reflection is pretty slow process. So, if you need high performance this may be a problem.
0
 

Author Closing Comment

by:sbornstein2
ID: 39187934
awesome thanks
0
 

Expert Comment

by:TtuRrv
ID: 39188068
I'm pretty certain there's a way to speed this up with some initial Expression Trees, but I have to get into a zen state of mind to tackle those.  However, there's another approach to using Reflection available in this case.  The code I'm attaching should hopefully explain it.

Basically, what I'm doing in this case is doing the reflection once, then storing a cache of the PropertyInfo values in a static List<> for later retrieval by other instances of the same class.

I've modified your code just a little bit for benchmarking purposes.  There's no real testing harness, just a handful of methods that need to be swapped out to get the timing values.  However, your original method minus the output is in the method "TestValuesOriginal()".  I refactored it in method "TestValuesRefactor1()" a bit to use LINQ heavily and it slowed down significantly at about a 75% increase in time.  I then modified that for the mthod "TestValuesRefactor2()" and got about a 25% decrease in time from the original method.

On my machine, the results for each method averaged as follows:
TestValuesOriginal: .008ms
TestValuesRefactor1: .014ms
TestValuesRefactor2: .006ms
Q-28135005.cs
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

597 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question