Home > database >  How to Convert a Entity to a List
How to Convert a Entity to a List

Time:12-08

I have an entity with only boolean Properties:

namespace MyProject.Entities
{
    public class MyEntity
    {
        
        public bool Bool2 { get; set; }
        public bool Bool2 { get; set; }
        public bool Bool2 { get; set; }

    }
}

Now I want do this:

using MyProject.Entities
namespace MyProject
{
    public class Program
    {

        public static void Main(string[] args)
        {
            MyEntity myEntity = new MyEntity()
            {
                Bool1=true,
                Bool2=false,
                Bool3=false
            }
            List<bool> Bool = myEntity.ToList(); //this doesn't run!
        }
    }
}

I need it first as Model, course I work in asp.net core mvc, and I get this model from a razor page. But now I need it as a list to check every prop. Can anyone help me?

The output that I need is a List with these three Booleans

CodePudding user response:

Here's what I'm talking about in the comments. First a class (with different property names - it does compile). I've added a ToBoolList method.

public class MyEntity
{
    public bool Bool1 { get; set; }
    public bool Bool2 { get; set; }
    public bool Bool3 { get; set; }

    public List<bool> ToBoolList()
    {
        return new List<bool> { Bool1, Bool2, Bool3 };
    }
}

To test this, run:

var testEntity = new MyEntity { Bool1 = true, Bool2 = false, Bool3 = true };
var boolList = testEntity.ToBoolList();

It will return a List<bool> containing true, false and true.

To do it with reflection, first you need to get the type of MyEntity, then its public instance properties, filtered so that only bools are returned. Finally, the code below gets each property's GetMethod and invokes it on the the object.

var testEntity = new MyEntity { Bool1 = true, Bool2 = false, Bool3 = true };
var entType = typeof(MyEntity);
var entProps = entType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var boolProps = entProps.Where(p => p.PropertyType == typeof(bool) && p.CanRead);
var boolReflectList = boolProps.Select(p => p.GetGetMethod().Invoke(testEntity, null)).Cast<bool>().ToList();

It also returns a List<bool> containing true, false and true. The first example should execute much faster.

CodePudding user response:

You can try to use the following code:

public static void Main(string[] args)
        {
            MyEntity myEntity = new MyEntity()
            {
                Bool1=true,
                Bool2=false,
                Bool3=false
            }
            List<bool> Bool = myEntity.GetType().GetProperties().Select(s=>s.GetValue(myEntity)).ToList();
        }

result: enter image description here

  • Related