繁体   English   中英

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

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

我希望在我的数据层中执行以下操作

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

这显然行不通。 C#将只让我返回IEnumerable,我希望公开的结构。

您不能使用匿名类型执行此操作。 您所追求的是.NET 4.0中的Tuple类型-您会这样写:

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

如果您不能使用.NET 4.0,则当然可以轻松地创建自己的等效项。

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

这将解决您的问题,同时又很有意义。

暂无
暂无

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

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