tags:

views:

79

answers:

2

Hello,

I wish to do something like the following in my data layer

public IEnumerable<{string,int}> ListIngredients()
        {
            return from i in RecipeIngredients select new {i.Ingredient.Name, i.Quantity};
        }

this obviously doesnt work. c# will only let me return IEnumerable and i wish to expose the structure.

+2  A: 

You can't do this using anonymous types. What you're after is the Tuple type from .NET 4.0 - you'd write:

public IEnumerable<Tuple<string,int>> ListIngredients()
{
    return RecipeIngredients.Select(i => Tuple.Create(i.Ingredient.Name,
                                                      i.Quantity));
}

You can fairly easily create your own equivalent of course, if you can't use .NET 4.0.

Jon Skeet
I thought of tuples but im on 3.5, so i will as you say create my own. Thanks
Mark
You can use KeyValuePair<TKey, TValue> instead of Tuple.
Tommy Carlier
@Tommy: I wouldn't, personally - I wouldn't regard this as a key/value pair; it's just a tuple. While the two types may behave the same way, I'd only use `KeyValuePair` when I'm dealing with a genuine key/value pair.
Jon Skeet
+3  A: 

May I suggest that you create a RecipeIngredient class (if you haven't already) that you can return from this method in the form of IEnumerable<RecipeIngredient>?

This will solve your problem, and at the same time, make sense.

TheObjectGuy