Ingweland
Ingweland

Reputation: 1077

How to pass property as parameter in C#

Suppose I have a class

class Item
{
    public int A {get; set}
    public int B {get; set}
    public int C {get; set}
} 

I have a method parseData(List<Item> items, <reference to property>) which should iterate through items and get only required property from each item. What is the most effective way to do it in C#. Should I use Expression for this (but I cannot figure out how to do it)?

Upvotes: 1

Views: 5595

Answers (2)

user7148391
user7148391

Reputation:

Some Reflection if you will

public void ParseData(List<Item> items, String PropertyName)
{
    foreach (Item item in items)
    {
        var prop = typeof(Item).GetProperty(PropertyName).GetValue(item, null);            
    }
}

Upvotes: 1

Sweeper
Sweeper

Reputation: 271390

To get a property, you could probably use a Func<Item, T>:

// I don't know what this method returns so I used "void".
public void ParseData<T>(List<Item> items, Func<Item, T> propertySelector) {
    // as an example, here's how to get the property of the first item in the list
    var firstItemsProperty = propertySelector(items.First());
    ...
}

You can call this method by passing a lambda expression:

ParseData(itemList, x => x.Property1) // "Property1" is a property declared in "Item"

Upvotes: 2

Related Questions