简体   繁体   English

linq从函数返回IEnumerable <{Object,Object}>

[英]linq returning IEnumerable<{Object,Object}> from a function

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. C#将只让我返回IEnumerable,我希望公开的结构。

You can't do this using anonymous types. 您不能使用匿名类型执行此操作。 What you're after is the Tuple type from .NET 4.0 - you'd write: 您所追求的是.NET 4.0中的Tuple类型-您会这样写:

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. 如果您不能使用.NET 4.0,则当然可以轻松地创建自己的等效项。

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>? 我是否可以建议您创建一个RecipeIngredient类(如果尚未创建),您可以以IEnumerable <RecipeIngredient>的形式从此方法返回?

This will solve your problem, and at the same time, make sense. 这将解决您的问题,同时又很有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM