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
Solved

C# + Simple List to Array question

Posted on 2013-05-21
8
224 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

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 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used.

792 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