开发者

Check if a property exists in a list of custom class

I have a list of my custom class(which has properties like Name,Age,Address).How can i check whether I have a property called "Name" in my list of custom class. I dont want to check if an item exists for the prop开发者_运维问答erty Name , rather i did like to check if the property exists or not.

Any help on this?


If you have a class named Foo and you want to check if a property Bar exists you can do the following using reflection:

bool barExists = typeof(Foo).GetProperties()
                            .Where(x => x.Name == "Bar")
                            .Any();

or shorter even (thanks for the reminder @Adam Robinson):

bool barExists = typeof(Foo).GetProperties().Any(x => x.Name == "Bar")


if(typeof(CustomClass).GetProperties().Where(i => i.Name == FieldYoureLookingFor).Count() > 0)
{
DoSomething();
}


Here a goes an object extension method that tell you whether a given PropertyName exists in any given object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StackOverflow.MyExtensions
{
    public static class ObjectExtentions
    {

        public static Boolean PropertyExists(this object Object, string PropertyName)
        {

            var ObjType = Object.GetType();

            var TypeProperties = ObjType.GetProperties();

            Boolean PropertyExists = TypeProperties
                    .Where(x => x.Name == PropertyName)
                    .Any();

            return PropertyExists;

        }

    }
}

Here goes a usage sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StackOverflow.MyExtensions;

namespace StackOverflow
{


    class Person
    {
        string _FirstName; // FirstName

        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }

        public string LastName;

    }


    class Program
    {

        static void Main(string[] args)
        {

            Person SamplePerson = new Person();

            if (SamplePerson.PropertyExists("FirstName"))
                Console.WriteLine("Yes! Property does exist!");
            else
                Console.WriteLine("Nope, property does not exist on object SamplePerson");

            if (SamplePerson.PropertyExists("LastName"))
                Console.WriteLine("Yes! Property does exist!");
            else
                Console.WriteLine("Nope, property does not exist on object SamplePerson");

        }
    }

}

Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜