LINQ to objects: Is there

Posted by Charles on Stack Overflow See other posts from Stack Overflow or by Charles
Published on 2012-03-23T17:21:11Z Indexed on 2012/03/23 17:29 UTC
Read the original article Hit count: 258

Filed under:
|
|
|

I cannot seem to find a way to have LINQ return the value from a specified accessor. I know the name of the accessors for each object, but am unsure if it is possible to pass the requested accessor as a variable or otherwise achieve the desired refactoring.

Consider the following code snippet:

// "value" is some object with accessors like: format, channels, language
row = new List<String> {
String.Join(innerSeparator, (from item in myObject.Audio
    orderby item.Key ascending
    select item.Value.format).ToArray()),
String.Join(innerSeparator, (from item in myObject.Audio
    orderby item.Key ascending
    select item.Value.channels).ToArray()),
String.Join(innerSeparator, (from item in myObject.Audio
    orderby item.Key ascending
    select item.Value.language).ToArray()),
// ...
}

I'd like to refactor this into a method that uses the specified accessor, or perhaps pass a delegate, though I don't see how that could work.

string niceRefactor(myObj myObject, string /* or whatever type */ ____ACCESSOR) {
    return String.Join(innerSeparator, (from item in myObject.Audio
            orderby item.Key ascending
            select item.Value.____ACCESSOR).ToArray());
}

I have written a decent amount of C#, but am still new to the magic of LINQ. Is this the right approach? How would you refactor this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ