Solved

C# + Simple List to Array question

Posted on 2013-05-21
8
228 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ASP.NET Built-In Report Creator / Viewer 5 38
CSS question 16 57
Send parameters via datatable ajax call 4 37
aspx ascx, c# 7 37
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

740 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