c# - Linq to Sql - SelectMany

标签 c# asp.net-mvc linq-to-sql

我正在尝试返回 List<Image>但我在使用以下方法时遇到了问题:

public List<Image> GetImageByCollection(int id)
    {
        List<Image> images = collectionDb.Images.SelectMany(i => i.CollectionId == id);
        return images;
    }           

我是 Linq 的新手,所以它可能是一些基本的东西,但希望你能看到我正在尝试做的事情。如果我不清楚,请说出来,我会尽力澄清。

最佳答案

你实际上是一个 Where 和 ToList

List<Image> images = collectionDb.Images
                             .Where(i => i.CollectionId == id).ToList();

Select 和 SelectMany 将返回 IEnumerable<T>的谓词。例如,

IEnumerable<int> collectoinIds = collectionDb.Images
                                             .Select(i => i.CollectionId);

现在 SelectMany 将“展平”对象列表。

public class Test
{
    IList<string> strings { get; set; } 
}

...

List<Test> test = new List<Test> 
{ 
    new Test { strings = new[] { "1", "2" } },
    new Test { strings = new[] { "3", "4" } },
};

IEnumerable<string> allStrings = test.SelectMany(i => i.strings);

allStrings包含“1”、“2”、“3”、“4”

关于c# - Linq to Sql - SelectMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9570297/

相关文章:

c# - MVC 4 Action 方法可为空的字符串参数需要错误

asp.net-mvc - 查找 System.Web.Mvc

javascript - 使用 AJAX 将 json 数据从 Google map 传递到 MVC Controller

c# - "Only arguments that can be evaluated on the client are supported for the String.Contains method"

c# - 复杂的 Linq-to-SQL where 条件帮助

c# - 序列化对象时到底发生了什么

c# - 使用unity 3D动态墙建模

c# - EF关系一对二

c# - 无法将类型 'System.Collections.Generic.IEnumerable<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<CUSTOM DATA TYPE>

C#反射绑定(bind)结果Linq2Sql to list