Tuesday, June 17, 2014

Extract Property Value from Object/Object Graph

The below code should be able to parse the object for respective property value and return back the value/null as response.Below type of string literals can be parsed with the below logic



            string s = "P[0].A";
            string g = "T[0].U.D";
            string t = "S[0].P[7].D";
            string NegativeValue = "P[0].WRONGVALUE";




public static Object GetPropertyValue(String name, object obj, Type type)
        {

            var isArray = false;

            var parts = name.Split('.').ToList();
            var currentPart = parts[0];
            var backup = parts[0]; ;

            int index = 0;
            if (currentPart.Contains(ArrayIdentifier))
            {
                // replace with some swift logic here -
                index = Int32.Parse(currentPart.Substring(currentPart.IndexOf('[')).Replace('[', ' ').Replace(']', ' ').Trim());
                currentPart = currentPart.Substring(0, currentPart.IndexOf('['));

            }

            PropertyInfo info = type.GetProperty(currentPart);

            if (info == null) { return null; }

            if (info.PropertyType.GetInterface("IEnumerable") != null)
            {
                int itemNb = 0;
                foreach (object item in (IEnumerable)info.GetValue(obj, null))
                {
                    if (itemNb == index)
                    {
                        parts.Remove(backup);
                        return GetPropertyValue(String.Join(".", parts), item, item.GetType());

                    }

                    //displayObject(item, displaySubObject, item.GetType);
                    itemNb++;
                }
                // index is not in range of the values provided
                throw new ArgumentOutOfRangeException();
            }

            if (name.IndexOf(".") > -1)
            {
                parts.Remove(backup);
                //if(!isArray)
                return GetPropertyValue(String.Join(".", parts), info.GetValue(obj, null), info.PropertyType);
                //else
                //    return GetPropValue(String.Join(".", parts), info.GetValue(obj, null), info.PropertyType,index);
            }
            else
            {
                if ((info.PropertyType.IsValueType || info.PropertyType.Equals(typeof(string))))
                {
                    return info.GetValue(obj, null).ToString();
                }

                else
                {
                    //return info.GetValue(obj, null).ToString();
                    return (null);
                }

            }
        }

No comments:

Post a Comment