Aleksei Chepovoi
Aleksei Chepovoi

Reputation: 3955

How to get Tuple property by property index in c#?

I need to implement Comparison delegate for Tuple. And I have a column number by which I want to compare Tuples.

For now I got to:

int sortedColumn;
Comparison<Tuple<T1, T2, T3>> tupleComparison = (x, y) =>
{
    // I want to access x.Item2 if sortedColumn = 2
        // x.Item3 if sortedColumn = 2 etc      
};

How can I do this in c#?

Can I do it without using switch?

Upvotes: 0

Views: 1692

Answers (2)

silkfire
silkfire

Reputation: 25935

A perhaps unknown fact is that all tuples implement the somewhat obscure interface ITuple. The interface defines two methods (Length returning the number of items in the tuple, and an index access method, [] - which is zero-based), but both of them are hidden, meaning that you have to explicitly cast your tuple variable to the implemented interface, and then use the relevant method.

Note that you have to cast the accessed item finally to its innate type, as the index access method always returns an object.

Comparison<Tuple<T1, T2, T3>> tupleComparison = (x, y) =>
{
    var columnValue = (int)((ITuple)x)[sortedColumn];     // Don't forget to cast to relevant type
};

Upvotes: 3

Tim S.
Tim S.

Reputation: 56536

I'd probably go with if/else or switch, but if you want to avoid that (e.g. so you can use it with any Tuple), you can use reflection:

Comparison<Tuple<T1, T2, T3>> tupleComparison = (x, y) =>
{
    var prop = typeof(Tuple<T1, T2, T3>).GetProperty("Item" + sortedColumn);
    var xItem = prop.GetValue(x);
    var yItem = prop.GetValue(y);
    return // something to compare xItem and yItem
};

Upvotes: 2

Related Questions