http://www.codinghelmet.com/  

Wear a helmet. Even when coding.

hints > linq-property-getter

How to Get Property Values using LINQ to Objects
by Zoran Horvat @zoranh75

Reflection lets us access members of an object, including property getters and setters. Through specialized methods we can read values from properties and write values back into them.

LINQ to Objects does not add any special ability regarding getting and setting property values. But LINQ makes it easy to filter the type members according to various criteria.

The following piece of code selects all read/write properties of integer type and converts them to name/value pairs. Name in each pair is the property name, while value is the actual value of the property. Here is the code:

IEnumerable<Tuple<string, int>> DehydrateObject(object obj)
{

    IEnumerable<Tuple<string, int>> values =
        (from property in obj.GetType().GetProperties()
            where property.PropertyType == typeof(int) &&
            property.CanRead &&
            property.CanWrite
            select new Tuple<string, int>(property.Name,
                                          (int)property.GetValue(obj)));

    return values;

}

Example

Below is the source code of a console application which demonstrates the DehydrateObject method. When function listed above is applied to an instance of the Rectangle structure, it extracts four integer properties that hold rectangle's location and size:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace PropertyGettingDemo
{
    class Program
    {

        static IEnumerable<Tuple<string, int>> DehydrateObject(object obj)
        {

            IEnumerable<Tuple<string, int>> values =
                (from property in obj.GetType().GetProperties()
                    where property.PropertyType == typeof(int) &&
                    property.CanRead &&
                    property.CanWrite
                    select new Tuple<string, int>(property.Name,
                                                  (int)property.GetValue(obj)));

            return values;

        }

        static void Main(string[] args)
        {

            Rectangle rect = new Rectangle(20, 30, 150, 90);

            IEnumerable<Tuple<string, int>> values = DehydrateObject(rect);
            Console.WriteLine("Rectangle={0}", rect);

            foreach (Tuple<string, int> value in values)
                Console.WriteLine("{0}={1}", value.Item1, value.Item2);

            Console.Write("Press ENTER to continue... ");
            Console.ReadLine();

        }
    }
}

The code produces output like this:

Rectangle={X=20,Y=30,Width=150,Height=90}
X=20
Y=30
Width=150
Height=90
Press ENTER to continue...

See also:

Published: Aug 5, 2013; Modified: Aug 8, 2013

ZORAN HORVAT

Zoran is software architect dedicated to clean design and CTO in a growing software company. Since 2014 Zoran is an author at Pluralsight where he is preparing a series of courses on design patterns, writing unit and integration tests and applying methods to improve code design and long-term maintainability.

Follow him on Twitter @zoranh75 to receive updates and links to new articles.

Watch Zoran's video courses at pluralsight.com (requires registration):

Tactical Design Patterns in .NET: Managing Responsibilities

Applying a design pattern to a real-world problem is not as straightforward as literature implicitly tells us. It is a more engaged process. This course gives an insight into tactical decisions we need to make when applying design patterns that have to do with separating and implementing class responsibilities. More...

Tactical Design Patterns in .NET: Control Flow

Improve your skills in writing simpler and safer code by applying coding practices and design patterns that are affecting control flow. More...

Improving Testability Through Design

This course tackles the issues of designing a complex application so that it can be covered with high quality tests. More...

Share this article

webmasters