Solved

C# + Simple List to Array question

Posted on 2013-05-21
8
215 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
  • 4
  • 3
8 Comments
 
LVL 29

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
 

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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 210 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 29

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Problem with SqlConnection 5 117
.NET Error 7 42
Asp/Net Validation date Issue 9 38
Re-position sub-options beneath the TAB 7 42
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
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.…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now