Linq to Sql - SelectMany

edi*_*ode 2 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;
    }           
Run Code Online (Sandbox Code Playgroud)

我是Linq的新手所以它可能是基本的东西,但希望你能看到我想要做的事情.如果我不清楚请说,我会尽力澄清.

Joe*_*Joe 8

你实际上是Where和ToList

List<Image> images = collectionDb.Images
                             .Where(i => i.CollectionId == id).ToList();
Run Code Online (Sandbox Code Playgroud)

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

IEnumerable<int> collectoinIds = collectionDb.Images
                                             .Select(i => i.CollectionId);
Run Code Online (Sandbox Code Playgroud)

现在,SelectMany将"展平"对象列表.

public class Test
{
    IList<string> strings { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

...

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);
Run Code Online (Sandbox Code Playgroud)

allStrings 包含"1","2","3","4"